SQL Table Edit: Add DateTime value in table - c#

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)";

Related

Get selected dataGridView column data?

C# Windows Form
I have a button that removes the selected row from the dataGridView.
I also want the button to retrieve the selected rows "ordre" column value, so I can use it in a query that deletes the order from the sql table.
Here is what my code looks like:
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//SQL connection
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
//SQL QUERY
command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = #ordre";
command.Parameters.AddWithValue("#ordre",dataGridView1.SelectedRows[0].Cells["ordre"].Value.ToString())
con.Open();
var ordre = command.ExecuteScalar();
con.Close();
But it doesn't work! No record was deleted
After delete the row you can not get the value. So change your code like this
//SQL connection
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt
+ "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security
Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
//SQL QUERY
command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = #ordre";
command.Parameters.AddWithValue("#ordre",dataGridView1.
SelectedRows[0].Cells["ordre"].Value.ToString())
con.Open();
var ordre = command.ExecuteScalar();
con.Close();
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
It is wrong logic.
Since the row has been removed by RemoveAt(),
you cannot get a wrong row from dataGridView1.SelectedRows[0].
I think you want this.
private void grdform1_CellClick(object sender, DataGridViewCellEventArgs e)
{
If(e.ColumnIndex==0 ||e.ColumnIndex==1)
{
txtshowcolunm.text=e.ColumnIndex;
}
else
{
txtshowcolunm.text=e.ColumnIndex;
}
}

ALTER TABLE in Access database from C#

I need to add datagridview data to a MS Access table, at the same time add a column into that table and update the column as well. please help me, I keep getting an error that says Syntax error in field definition and then says No value given for one or more required parameters.
private void button1_Click(object sender, EventArgs e)
{
string myConnectionString = " ";
myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/game/Desktop/3rd year/2nd Semester/INYM 328/EmployeeAttendanceRegister/EmployeeAttendanceRegister/EmployeeAttendanceRegister.accdb";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col4 = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col5 = dataGridView1[4, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col6 = dataGridView1[5, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col7 = dataGridView1[6, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string myInsertQuery = "INSERT INTO Attendance VALUES('" + col1 + "','" + col2 + "','" + col3 + "','" + col4 + "','" + col5 + "','" + col6 + "','" + col7 + "')";
OleDbCommand myCommand = new OleDbCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
myConnection.Close();
{
string myConn = " ";
myConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/game/Desktop/3rd year/2nd Semester/INYM 328/EmployeeAttendanceRegister/EmployeeAttendanceRegister/EmployeeAttendanceRegister.accdb";
OleDbConnection myCon = new OleDbConnection(myConn);
string myInsert = "ALTER TABLE Attendance ADD COLUMN SignIn";
OleDbCommand myCom = new OleDbCommand(myInsert);
myCom.Connection = myCon;
myCon.Open();
try
{
myCom.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
myCon.Close();
}
{
string myString = " ";
myString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/game/Desktop/3rd year/2nd Semester/INYM 328/EmployeeAttendanceRegister/EmployeeAttendanceRegister/EmployeeAttendanceRegister.accdb";
OleDbConnection myConnect = new OleDbConnection(myString);
string Insert = "UPDATE Attendance SET SignIn = '" + dateTimePicker1.Value + "'";
OleDbCommand myComm = new OleDbCommand(Insert);
myComm.Connection = myConnect;
myConnect.Open();
try
{
myComm.ExecuteNonQuery();
MessageBox.Show("Successfully Signed IN");
frmhomepage previousForm = new frmhomepage();
previousForm.Show();
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
myConnect.Close();
}
}
I keep getting an error that says Syntax error in field definition
That's probably because the ALTER TABLE statement
ALTER TABLE Attendance ADD COLUMN SignIn
does not specify the column type. Based on the UPDATE command that follows, you probably meant
ALTER TABLE Attendance ADD COLUMN SignIn DATETIME
However, there are other problems with your code, too:
Why are you trying to ALTER TABLE after every button click? Once you've changed the structure of the [Attendance] table you don't need to do it again.
You are trying to pass a date/time value delimited with single quotes ('). Access SQL normally expects date/time values to be delimited with hash marks (#).
Instead of "gluing SQL statements together" you should use parameterized queries to help you avoid delimiter problems (see above) and protect you from SQL Injection.

Excel from string data to integer

I add data from a text to excel with insert into, but it's always show string format. I want it float format(0.2, 1, 20) and I cant change them in excel (for example a coloumn in one time, only it could be changed by one by for all cells). I tried tryparse or converttoint32 func. but nothing change in excel, the numbers are still in text format..
public void ExcelWrite(string date, string station_name, string station_no, string xvaluee)
{
try
{ float j;
xvaluee=xvaluee.Trim();
float.TryParse(Valuee, out j);
string szConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C://data.xls';Extended Properties='Excel 8.0;HDR=YES'";
OleDbConnection conn = new OleDbConnection(szConn);
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES('" + station_no + "','" + station_name + "','" + date + "','" + j + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
since you adding '' for each parameter all will take as strings
use Parameters as below
using(OleDbConnection cn = new OleDbConnection(szConn ))
{
cn.Open();
OleDbCommand cmd1 = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES(?,?,?,?)", cn);
cmd1.Parameters.AddWithValue("#p1", station_no );
cmd1.Parameters.AddWithValue("#p2", station_name );
cmd1.Parameters.AddWithValue("#p3",date );
cmd1.Parameters.AddWithValue("#p4", j);
cmd1.ExecuteNonQuery();
}

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();
}

update null for type date

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();
}

Categories

Resources