Input string was not in a correct format - mysql

Can anyone please advise where i have gone wrong with the following method / stored proceedure? I keep getting the following error...
**
> Input string was not in a correct
**
This is the Stored proceedure i using and the method.
-- --------------------------------------------------------------------------------
-- Routine DDL
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`Admin`#`%` PROCEDURE `test`(
IN p_idExceptionLog INT(32) ,
IN p_ExceptionDate DATETIME ,
IN p_User VARCHAR(45) ,
IN p_ExceptionMessage VARCHAR(4000)
)
BEGIN
INSERT INTO ExceptionLog
(
id ,
Date ,
User ,
Message
)
VALUES
(
p_idExceptionLog ,
p_ExceptionDate ,
p_User ,
p_ExceptionMessage
) ;
END
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
// MySqlCommand inputError1 = new MySqlCommand();
MySqlCommand inputError = null;
int rows = 0;
string spName = "test";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (1)));
inputError.Parameters[0].Value = "";
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}
Thanks

Err you are declaring paramter[0] (idExceptionLog) as an Int32 and then setting it to a string in your script? perhaps not setting it will help if it's supposed to be auto-generated or giving it a valid int value if you are manually generating it.

Worked the problem out.
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
MySqlCommand inputError = null;
int rows = 0;
string spName = "ExceptionInsert";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (0)));
inputError.Parameters[0].Value = null;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}

Related

Update stored procedure in mysql does not work with asp.net?

Here's my code :
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (pass1.Text != pass2.Text)
{
lblerror.Text = "Passwords do not match.";
}
else
{
DB db = new DB();
string pass = db.Encrypt(pass2.Text.Trim());
MySqlConnection sqlcon = new MySqlConnection(db.sqlstring());
MySqlCommand cmd = new MySqlCommand("changepassword", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.Add(#"pass", MySqlDbType.VarChar).Value = pass;
cmd.Parameters.Add(#"user1", MySqlDbType.Int16).Value = Convert.ToInt16(Session["userKey"]);
sqlcon.Open();
cmd.ExecuteNonQuery();
//Response.Redirect("regex.aspx", false);
//Context.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
finally
{
sqlcon.Close();
Session.Abandon();
Session.RemoveAll();
}
}
}
and My stored procedure is like this.
delimiter $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `changepassword`(IN pass varchar(100),IN user1 varchar(100))
begin
update users set Password = 'pass' where UserID = user1;
end;
When I update using call in mysql workbench it works well.
But when I call from backend in asp.net
The value of password is changed 'pass' in table but not actual value which is passed as 'string = pass';
What is wrong in my code? I didn't find any exception in above code.

Stored Procedures With optional parameters MVC4

I have a stored procedure with some optional parameters.....I pass a type parameter and depending on that i invoke the appropriate query.
Following is my query
create procedure [dbo].[usp_InsertInfo]
#login_id varchar(500)=null,
#login_name varchar(200)=null,
#handler_name varchar(500)=null,
#city varchar(100)=null,
#email varchar(500)=null,
#img_url_http varchar(max)=null,
#img_url_https varchar(max)=null,
#token varchar(500)=null,
#login_type varchar(2)=null
as
begin
if(#login_type='F')
//code goes here
else
//code goes here
end
And here is the way i am calling it from my controller
using (Entities dbContext = new Entities())
{
var parameters = new SqlParameter[7];
parameters[0] = new SqlParameter { ParameterName = "login_id", Value = objUser.Id };
parameters[1] = new SqlParameter { ParameterName = "login_name", Value = objUser.Name };
parameters[2] = new SqlParameter { ParameterName = "handler_name", Value = objUser.ScreenName };
parameters[3] = new SqlParameter { ParameterName = "img_url_http", Value = objUser.ProfileImageUrl };
parameters[4] = new SqlParameter { ParameterName = "img_url_https", Value = objUser.ProfileImageUrlHttps };
parameters[5] = new SqlParameter { ParameterName = "token", Value = accessToken.Token };
parameters[6] = new SqlParameter { ParameterName = "login_type", Value = "T" };
List<userInfo> objUserInfo = dbContext.ExecuteStoreQuery<userInfo>("usp_InsertInfo #login_id,#login_name,#handler_name,#img_url_http,#img_url_https,#token,#login_type", parameters).ToList();
}
But when i check the values in Database the values are messed up...
In img_url_http i get the token value img_url_https i get the type value and so on.
M confused like where m i going wrong or wether MVC4 doesnot support null parameters.
Or please help me with the proper way of calling the stored procedure through MVC4 with optional parameters
I want to run this code with the optional parameters and execute the store procedure and return the results depending upon the conditions.
static void CallAProcedure(int required, int? optional)
{
string connectionstring = "connection string here.";
using (SqlConnection cn = new SqlConnection(connectionstring))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandText = "AProcedure";
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("#Required", 1);
if (optional.HasValue)
cm.Parameters.AddWithValue("#Optional", optional.Value);
cm.ExecuteNonQuery();
}
}
}

Getting return value from dynamic sql from stored procedure (SQL Server and C# ADO.NET)?

I created a stored procedure to get return value from a dynamic sql. I get the following exception:
String[1]: the Size property has an invalid size of 0.
My proc:
CREATE proc [dbo].[Review_Get_PrePopValue](#sqlQuery nvarchar(500), #display nvarchar(200) OUTPUT)
as
EXEC sp_executesql #sqlQuery,
#display OUTPUT
My Code:
public string GetAnswerValue(string contentSQL, string parameter, string parameterValue)
{
string sqlstatement = contentSQL.Replace(parameter, parameterValue);
using (var conn = new SqlConnection(_connectionString))
{
string prePopValue;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "Review_Get_PrePopValue";
comm.Parameters.Add(new SqlParameter("#sqlQuery", SqlDbType.NVarChar)).Value = sqlstatement;
comm.Parameters.Add(new SqlParameter
{
Direction = ParameterDirection.Output,
ParameterName = "#display",
SqlDbType = SqlDbType.NVarChar
});
conn.Open();
comm.ExecuteNonQuery();
prePopValue = comm.Parameters["#display"].Value.ToString();
return prePopValue;
}
}
My sql string:
Select #display = Grant_Number From GMIS_Grants where grant_id=1
Direction = ParameterDirection.Output, ParameterName = "#display", Size = 200, SqlDbType = SqlDbType.NVarChar
Needed to set the size for nvarchar
From MSDN
For bidirectional and output parameters, and return values, you must set the value of Size.
Also, add this at the end of your SP.
SELECT #display;

MySQL System.FormatException: Input string was not in a correct format

Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.

The SqlParameterCollection only accepts non-null SqlParameter type objects, not MySqlParameter objects

I have created a method that will insert any exceptions thrown into a table on "ExceptionLog" on MySql server.
ExceptionLog Table format
idExceptionLog int (AI)
User (varchar 45)
ErrorMessage (varchart 4000)
The problem is i keep getting the following error. Does anyone know why?
The SqlParameterCollection only
accepts non-null SqlParameter type
objects, not MySqlParameter objects.
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
SqlConnection NasDB = null;
SqlCommand inputError = null;
int rows = 0;
string spName = "ExceptionInsert";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new SqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new SqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[0].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[1].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[2].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
All the classes inside System.Data.SqlClient are used for SQL Server database & not mysql.
In your code, replace SqlCommand with MySqlCommand and SqlConnection with MySqlConnection.
EDIT: See this page for the classes, you could use in this case.
I have made some slight changes and am now getting the following error.
**
Input string was not in a correct
**
This is the Stored proceedure i using and the method.
-- --------------------------------------------------------------------------------
-- Routine DDL
DELIMITER $$
CREATE DEFINER=Admin#% PROCEDURE test(
IN p_idExceptionLog INT(32) ,
IN p_ExceptionDate DATETIME ,
IN p_User VARCHAR(45) ,
IN p_ExceptionMessage VARCHAR(4000)
)
BEGIN
INSERT INTO ExceptionLog
(
id ,
Date ,
User ,
Message
)
VALUES
(
p_idExceptionLog ,
p_ExceptionDate ,
p_User ,
p_ExceptionMessage
) ;
END
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
// MySqlCommand inputError1 = new MySqlCommand();
MySqlCommand inputError = null;
int rows = 0;
string spName = "test";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (1)));
inputError.Parameters[0].Value = "";
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}