SET Parameter DateTime - c#

I need set the parameter date for compare on a SQL Server table.
Where the day, month and year he will add the QUANTIDADE and weight of fish.
But giving this a mistake and falling in the catch and can not set it.
DATA_REGISTRO is a Date datatype in SQL Server.
Code:
public void Search_DATE(string param_date)
{
SqlDataReader objReader;
SqlCommand objcmd = null;
vsql = "SELECT [IDCADASTRO],[RGP],[PEIXE],[PESO],[QUANTIDADE],[DATA_REGISTRO] FROM cadastro WHERE DATA_REGISTRO LIKE #DATA_REGISTRO";
if (this.Conectar())
{
try
{
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", param_date));
objReader = objcmd.ExecuteReader();
if (objReader.Read())
{
valor.retorna_date_time = objReader.GetDateTime(5).ToString;
}
}
catch (SqlException erro)
{
throw erro;
}
finally
{
this.Desconectar();
}
}
Global Variable
private static string date_time;
public string retorna_date_time
{
get { return date_time; }
set { date_time = value; }
}

DATA_REGISTRO is a Date type on SQL
However, you are supplying a string parameter
public string retorna_date_time
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", param_date));
Instead, supply a DateTime parameter
DateTime dtParam = DateTime.Parse(param_date);
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", dtParam));
Also, it is not a good idea to catch an exception unless you will do something with it
catch (SqlException erro)
{
throw erro;
}
I understand you may have that line in there for debugging, but remove it from your final code unless there is something you can do with the exception.

Pass the Date of you param_date.
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", Convert.ToDateTime(param_date).Date));

Related

Method Returning only " "

I need return string of DateTime. More this method is returning only null
receives an input string, convert to DateTime and i need put DateTime on valor.retorna_date_time string variable.
Code:
public void Search_DATE(string param_date)
{
SqlDataReader objReader;
SqlCommand objcmd = null;
vsql = "SELECT [IDCADASTRO],[RGP],[PEIXE],[PESO],[QUANTIDADE],[DATA_REGISTRO] FROM cadastro WHERE DATA_REGISTRO LIKE #DATA_REGISTRO";
if (this.Conectar())
{
try
{
DateTime dtParam = DateTime.Parse(param_date);
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", dtParam));
objReader = objcmd.ExecuteReader();
if (objReader.Read())
{
valor.retorna_date_time = objReader.GetString(6);
}
}
catch (SqlException erro)
{
throw erro;
}
finally
{
this.Desconectar();
}
}
}
Input Parameters:
DateTime myDateTime = DateTime.Now;
string DateTimesql = myDateTime.ToString("dd-MM-yyyy");
objSQL.Search_DATE(DateTimesql);
valor.retorna_date_time is a global string variable.
Your SELECT statement returns 6 columns:
[IDCADASTRO],[RGP],[PEIXE],[PESO],[QUANTIDADE],[DATA_REGISTRO]
But IDatareader's GetString(n) method is 0-based, so GetString(6) returns the 7th column, which there isn't.
Change it to GetString(5).
Without seeing your table structure, I would try GetOrdinal.
Change
valor.retorna_date_time = objReader.GetString(6)
to
valor.retorna_date_time = objReader.GetOrdinal("DATA_REGISTRO");
Since you only seem to need just the last column, you can change your query to:
"SELECT [DATA_REGISTRO] FROM cadastro WHERE DATA_REGISTRO LIKE #DATA_REGISTRO";
And then read it using ExecuteScalar
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.AddWithValue("#DATA_REGISTRO", dtParam);
valor.retorna_date_time = objcmd.ExecuteScalar().ToString();
EDIT:
ExecuteScalar() will return a null reference if the query did not return anything.
You should check if it is null before converting it to string and passing it to valor.retorna_date_time. Do something like:
string returnValue = objcmd.ExecuteScalar() == null ?? String.Empty : objcmd.ExecuteScalar().ToString();

Error on Parameter C# SQL

I need verify the Parameter RGP, PEIXE, DATA_REGISTRO for my method return true. But on PEIXE parameter this giving error:
Expects 'PEIXE' parameter, which was not provided.
PEIXE is a Varchar type on SQL, RGP is a Int type and DATA_REGISTRO is a Date type.
public bool Search_RGP_Cadastro(int param_RGP, string param_date, string param_peixe)
{
SqlDataReader objReader;
SqlCommand objcmd = null;
vsql = "SELECT [RGP], [PEIXE], [PESO], [QUANTIDADE], [DATA_REGISTRO] FROM cadastro WHERE RGP = #RGP and PEIXE = #PEIXE and DATA_REGISTRO = #DATA_REGISTRO";
if (this.Conectar())
{
try
{
DateTime dtParam = DateTime.Parse(param_date);
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("#RGP", param_RGP));
objcmd.Parameters.Add(new SqlParameter("#PEIXE", param_peixe));
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", dtParam));
objReader = objcmd.ExecuteReader();
if (objReader.Read())
{
valor.retorna_RGP = objReader.GetInt32(0);
valor.retorna_nome_peixe = objReader.GetString(1);
valor.retorna_peso = objReader.GetDouble(2);
valor.retorna_Quantidade = objReader.GetInt32(3);
valor.retorna_date_time = objReader.GetDateTime(4);
}
return true;
}
catch
{
throw;
}
finally
{
this.Desconectar();
}
}
else
return false;
}
I'd wrap your param_peixe in single quotes, like this:
objcmd.Parameters.Add(new SqlParameter("#PEIXE", "'" + param_peixe + "'"));
It wouldn't be the first time I've seen SQL reject the use of a string as a VARCHAR.

Error-Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'

I am developing an application to transfer data between two databases in C#. I have a method to insert BLOB type data in MySQL. While executing it I am getting error Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'.
Code#
public static void FiletoSql(MemoryStream fileToPut, MySqlConnection con)
{
try
{
const string preparedCommand =
#"update user_account_statement set STATEMENT_FILE=#ssfile, create_date_time=#udatetime where statement_Id=1070";
using (var sqlWrite = new MySqlCommand(preparedCommand, con))
{
sqlWrite.Parameters.AddWithValue("#ssfile", MySqlDbType.Blob).Value = fileToPut.ToArray();
sqlWrite.Parameters.AddWithValue("#udatetime", MySqlDbType.DateTime).Value =
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
sqlWrite.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am not getting exactly what is problem in converting.
Edit: I've tried this:
var fileData=new MySqlParameter("#ssfile",MySqlDbType.Blob,data.Length) {
Value = data
};
sqlWrite.Parameters.Add(fileData);
sqlWrite.Parameters.AddWithValue("#udatetime", MySqlDbType.DateTime)
.Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
var cmd = sqlWrite;
sqlWrite.ExecuteNonQuery();
And now I am getting error Input string was not in a correct format.
Wow!! Got the answer.
Tested solution:
public static void FiletoSql(MemoryStream fileToPut, MySqlConnection con)
{
byte[] data = fileToPut.ToArray();
try
{
const string preparedCommand =
#"update user_account_statement set STATEMENT_FILE=#ssfile, create_date_time=#udatetime where statement_Id=1070";
using (var sqlWrite = new MySqlCommand(preparedCommand, con))
{
sqlWrite.Parameters.Add("#ssfile", MySqlDbType.Blob);
sqlWrite.Parameters.Add("udatetime", MySqlDbType.DateTime);
sqlWrite.Parameters["#ssfile"].Value = data;
sqlWrite.Parameters["udatetime"].Value=DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
sqlWrite.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Cannot convert input string to Int64 in ASP.NET using store procedures

I have used the store procedure in MS-Sql for inserting for particular page it is working fine but I also need the same store procedure for other page it is finding me the error.
protected void btnsubmitt_Click(object sender, EventArgs e)
{
ArrayList arParameters = ReturnParameter();
DataSet dsInsertProfile = objadmin.GetGridData(arParameters, objconstant.sSP_INSERT_PROFILE);
if (int.Parse(dsInsertProfile.Tables[0].Rows[0].ItemArray[0].ToString()) == 0)
{
pnlProfile.Visible = false;
pnlThank.Visible = true;
lblThank.Text = "Your profile have been successfully saved.";
}
else
{
lblThank.Text = "Your profile is not saved, please try again later.";
}
}
public ArrayList ReturnParameter()
{
Int64 email = Convert.ToInt64(txtemail.Text.ToString());
ArrayList arSample = new ArrayList();
Object[] c_email_id = new Object[3] { "#strEmailID", "varchar", email};
arSample.Add(c_email_id);
return arSample;
}
public DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
dsDataSet = datamanager.GetGridData(dbArray, sSpName);
return dsDataSet;
}
public static DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
SqlConnection cn = createConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sSpName;
object objPrMtrName;
object objSqlType;
object objPrMtrVal;
int i;
for (i = 0; i < dbArray.Count; i++)
{
objPrMtrName = ((object[])(dbArray[i]))[0];
objSqlType = ((object[])(dbArray[i]))[1];
objPrMtrVal = ((object[])(dbArray[i]))[2];
cmd.Parameters.Add(objPrMtrName.ToString(), GetSqlDataType(objSqlType.ToString())).Value = objPrMtrVal;
}
cmd.Connection = cn;
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
return dsDataSet;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
}
Mystore procedure
ALTER Procedure [dbo].[spInsert_profile]
( #strEmailID varchar(200)
)
AS
BEGIN
DECLARE #intEmail INT
SET #intEmail = (SELECT COUNT(*) FROM gdt_Users WHERE [c_email_id]=#strEmailID)
IF #intEmail = 0
BEGIN
Insert into gdt_Users([c_email_id],[d_modified_dttm],[d_created_dttm])values(#strEmailID,GETDATE(),GETDATE())
SELECT #intEmail
END
ELSE
BEGIN
SELECT #intEmail
END
END
Here, I was facing a problem. It was throwing an exception
ERROR: Failed to convert parameter value from string to Int64
So, I've add this code
Int64 email = Convert.ToInt64(txtemail.Text.ToString());
in arraylist returnparameter() method. Then, it threw that exception
ERROR: Input string was not in correct format
How can I solve this? Can you help me?
In your code I can find Convert.ToInt64 only at one place which is
Int64 email = Convert.ToInt64(txtemail.Text.ToString());
You would not be passing valid number to Convert.ToInt64( as txtemail will have string not a number. You should give a number in txtemail or use the correct textbox for converting the string to int64.
Keep in mind Convert.ToInt64( converts string to number only if the
string is number.
Your stored procedure expects varchar(200) which is equivalent to String of length 200, so email should be string and not number. E.g. yourname#someemail.com is a string. Am just curious, what makes you think is int64. It should be
string email = txtemail.Text;
Your code down here indicates email should be string by using "varchar"
string email = txtemail.Text; //change your code to this
ArrayList arSample = new ArrayList();
Object[] c_email_id = new Object[3] { "#strEmailID", "varchar", email};

Static class method doesn't return value

I have following code (this is just for demonstration, I won't paste all lines)
public static class SearchAndEdit
{
public static string[] SearchAndDisplay(string code)
{
string SQLconnection = WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
string[] field;
field = new string[6];
if (code == "")
{
field[0] = "Nothing to search";
}
else
{
string SQLSelect = "SELECT user_name, user_surname, user_code, user_group, user_password FROM Users WHERE user_code=#user_code";
SqlConnection connect = new SqlConnection(SQLconnection);
SqlCommand search = new SqlCommand(SQLSelect, connect);
search.Parameters.Clear();
search.Parameters.AddWithValue("#user_code", code);
try
{
connect.Open();
SqlDataReader info = search.ExecuteReader();
if (info.HasRows)
{
field[0] = "Data loaded";
}
}
finally
{
connect.Close();
}
}
return field;
}
}
Then I use it in Code behind file (*aspx.cs).
protected void Search_click(object sender, EventArgs e)
{
string[] information = SearchAndEdit.SearchAndDisplay(searchBox.Text);
for (int i = 0; i < information.Length; i++)
{
name.Text += information[i];
}
}
However, the code returns nothing (label name is empty), even exception is not thrown. Any idea where is the catch ? Thanks.
try this
if(string.IsNullOrEmpty(code))
{
field[0] = "Empty box";
}
you changed the post. you should have this instead
string SQLconnection = WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
string[] field;
field = new string[6];
field[0] = "Nothing to search"; // add here in case string is null
if (!string.IsNullOrEmpty(code))
{
string SQLSelect = "SELECT user_name, user_surname, user_code, user_group, user_password FROM Users WHERE user_code=#user_code";
SqlConnection connect = new SqlConnection(SQLconnection);
SqlCommand search = new SqlCommand(SQLSelect, connect);
search.Parameters.Clear();
search.Parameters.AddWithValue("#user_code", code);
try
{
connect.Open();
SqlDataReader info = search.ExecuteReader();
if (info.HasRows)
{
field[0] = "Data loaded";
}
}
catch
{
// error handle here problem with connection
}
finally
{
connect.Close();
}
}
return field;
Well, now that you've shown us more code: if the SQL query returns 0 rows, then the returned array will be empty, as you observe. Therefore, it seems that the values you're passing in for user_code aren't in the database -- or perhaps they're of the wrong data type.
You should try stepping through this with a debugger. There is a case where the field array will return an array of six null string elements: if code is not an empty string, the else clause will execute, and if your SQL query returns no rows, then field will never receive any string values. My guess is that this is what's happening. If you can't use a debugger for some reason (?), you can always modify your code thusly:
if (info.HasRows) {
field[0] = "Data loaded";
} else {
field[0] = "No data found";
}

Categories

Resources