update null for type date - c#

I have a sentence follow:
string strSQL = "update pl_poli set ag_vouch = ' ',ag_vdate = #, ag_vmode = null where
pl_no = '" + textBox5.Text + "' and pl_endtno ='" + textBox6.Text + "'";
I can't update because error "data type mismath". i have fill ag_vdate is type date
I want to Update it -> null
Please can you help me. Thank you so much.

In your case you cannot pass " # " at datetime column because sql server consider this as varchar value and not able to convert this in datetime so...
Try to do as below
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO table1 (column1, column2) VALUES (#param1, #param2)";
command.Parameters.Add("#param1", SqlDbType.DateTime).Value =
DateTime.TryParse(txtDate.Text, out d) ?
(object)d :
DBNull.Value // inserting NULL
...
connection.Open();
command.ExecuteNonQuery();
}

Related

how to get data between two dates from sql server 2008 in asp.net

I'm using referenced date-picker control to select date. I get the error
Conversion failed when converting date and/or time from character string
public DataSet comsn(string x, DatePickerControl.DatePicker a, DatePickerControl.DatePicker b)
{
ConnectionStringSettings connectionstringsql = ConfigurationManager.ConnectionStrings["plprojectConnectionString"];
SqlConnection connectionsql = new SqlConnection(connectionstringsql.ConnectionString);
if (connectionsql.State != System.Data.ConnectionState.Open)
{
connectionsql.Open();
}
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "comm"); //<------ At this line error occurred [ Conversion failed when converting date and/or time from character string ]
adp.Dispose();
return ds;
}
You can make this work by controlling the date format. When supplied to sql server as a string, I always format my data only string using 'YYYY-MM-DD', i.e., using the ToString('yyyy-MM-dd') on a date field.
However, you are better of turning your query into a parameter driven sql.
i.e., instead of "date >= '" a.Calendardate.ToString("yyyy-MM-dd")
Use "date >= #ADate"
and the supply the parameter value as
cmd.Parameters.Add("ADate", SqlDbType.DateTime).Value = a.Calendardate
I am assuming your datepicker has a "DateTime" property I am treating a.Calendardate as the DateTime property
You can avoid the exception and sql injection by using a parameterized query.
Replace:
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
With:
string sql = "select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= #x AND date>= #a AND date <= #b "
var cmd = new SqlCommand(sql);
cmd.Parameters.Add("#x", SqlDbType.NVarChar, x);
cmd.Parameters.Add("#a", SqlDbType.DateTime, a);
cmd.Parameters.Add("#b", SqlDbType.DateTime, b);
cmd.Connection = connectionsql;

SQL Table Edit: Add DateTime value in table

I made SQL table editor for add info in some columns. But one column is set to "DateTime" in and application can't write it . Here is the code:
private void button2_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end) VALUES (#char_id, #status, DateTime #ban_date, #ban_hour, #ban_end)";
command.Parameters.AddWithValue("#char_id", "1");
command.Parameters.AddWithValue("#status", "1");
command.Parameters.AddWithValue("#ban_date", "1");
command.Parameters.AddWithValue("#ban_hour", "1");
command.Parameters.AddWithValue("#ban_end", "1");
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Char Banned");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Column 'ban_date' is set to DateTime.
Thank you!
"1" is not a date. Try passing a date to it
command.Parameters.AddWithValue("#ban_date", DateTime.Today);
And remove the DateTime from the command string
command.CommandText = "INSERT INTO user_ban
(char_id, status, ban_date, ban_hour, ban_end)
VALUES
(#char_id, #status, #ban_date, #ban_hour, #ban_end)";
If ban_date column is DateTime, why you want to insert 1 to it? Does not make sense. 1 is not a valid DateTime at all. Change it to a valid DateTime value.
Second, you should not use value type in your VALUES part. Change it from
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
VALUES (#char_id, #status, DateTime #ban_date, #ban_hour, #ban_end)";
^^^^^^^^^//delete this
to
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
VALUES (#char_id, #status, #ban_date, #ban_hour, #ban_end)";

Insert DateTime into Sql Server 2008 from C#

I've been trying to get this right for over 2hrs so any help is highly appreciated
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}
So basically what that does is insert a datetime into an sql server table keeping the same format of the month and day to avoid regional settings getting in the way.
The only problem is that the time remains 00:00:00. Even though when I debug the code, 'appt' shows 28/06/2013 09:30:00
try below
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = ? WHERE ID = ?";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.Parameters.AddWithValue("#p1", appt);
updateCommand.Parameters.AddWithValue("#p2", studentID);
updateCommand.ExecuteNonQuery();
connection.Close();
}
BUT!
You say it is sql server but why you using OleDbCommand ?
try below if it is sql server
public void setAppointment(int studentID, DateTime appt)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE dbo.students SET appointmentDate = #appointmentDate WHERE ID = #ID";
con.Open();
cmd.Parameters.AddWithValue("#appointmentDate", appt);
cmd.Parameters.AddWithValue("#ID", studentID);
cmd.ExecuteNonQuery();
}
}
Line 5.
Change
... appt.Date.ToString(...
to
... appt.ToString(...
I hope you have solved your problem from previous post and I agree SQL Statements to be used with parameters.
If you have an application date time format is fixed, then there is no harm in hard-coding but it would be good code to get date time format from your web.config file. This will help your code to be same consistent overall project.
Instead of
ToString("yyyy-MM-dd HH:mm:ss")
ToString(ConfigValue)
Too Late, But for your question : Try the code below.
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + "CONVERT(datetime, '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "', 103)" + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}

selecting data between 2 dates

I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'

Getting Data from Access into a text box in C# by clicking a button

I have a table in MS Access that contain: (FoodID, FoodName, Price).
In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch).
My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .
Please solve this problem for me. This is the whole source code that I got for you.
System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
txtName.Text = dr["FoodName"].ToString();
txtPrice.Text = dr["Price"].ToString();
}
dr.Close();
conn.Close();
I assume FoodID is int. You should remove single quotes in this case
cmd.CommandText = "select FoodName, Price from tablename where FoodID = " + txtId;
Even better - use parameters:
using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "select FoodName, Price from tablename where FoodID = #FoodID";
command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = reader["FoodName"].ToString();
txtPrice.Text = reader["Price"].ToString();
}
}
I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;
There seems to be no problem with this line of code :
OleDbDataReader dr = cmd.ExecuteReader();// correct way
I think the problem is in:
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
You need to use the .Text Propertie of the Textbox
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";

Categories

Resources