I am having trouble updating data into a table from my C# form. Could someone tell me what I am doing wrong. It does not give me an error and says that it has been submitted successfully. My database show no change however.
try
{
string cmdstring = "UPDATE Test SET COLLECTION_DATE = '#date', SPECIMANID = '#spec', TEST_RESULT = '#result', SUBSTANCE_RESULT = '#substance' WHERE PEOPLESOFT_EMPL_ID = #empID ;";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.Add("#date", OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#spec", OleDbType.Char).Value = textBoxSpec.Text;
cmd.Parameters.Add("#result", OleDbType.Char).Value = comboBoxResult.Text;
cmd.Parameters.Add("#substance", OleDbType.Char).Value = comboBoxSubstance.Text;
cmd.Parameters.Add("#empID", OleDbType.Char).Value = textBoxID.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
Problem : You are enclosing the Parameters in your update query within single quotes.
Solution : while using parameterised queries you should not enclose the parameters within single quotes, so you need to remove the single quotes around the parameters in update query.
Try This:
string cmdstring = "UPDATE Test SET COLLECTION_DATE = #date, SPECIMANID = #spec,
TEST_RESULT = #result, SUBSTANCE_RESULT = #substance WHERE PEOPLESOFT_EMPL_ID =
#empID ;";
Suggestion: You are displaying the success mesaage without checking the query execution status.
i would suggest you to verify the ExecuteNonQuery() return value before displaying the Success message.
From MSDN :ExecuteNonQuey()
Executes a Transact-SQL statement against the connection and returns
the number of rows affected.
Try This:
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
MessageBox.Show("Records Inserted Successfully!");
else
MessageBox.Show("Insertion Failed!");
Related
I tried to do begin transaction on SQL Server, but it returns an error that I can't figure out what the real problem is. So here is some of my code I tried.
This is the error:
Code:
SqlConnection connection = new SqlConnection("Data Source=LOCALHOST\\SQLEXPRESS;Initial Catalog=tempdb;Integrated Security=SSPI;User ID = xxxx; Password=xxx;");
DateTime dt = dateTimePicker1.Value.Date;
dt = dt.AddDays(60);
string selectQuery = "BEGIN TRANSACTION UPDATE tester SET
test_ad=#dateTimePicker1, test_ud=#dt, test_pd=#dt WHERE
test_name=#textBox1;INSERT INTO records(testr_status, testr_name, testr_ad,
testr_ud, testr_pd, apte_name)VALUES(#testr_status, testr_name = #comboBox1,
testr_ad = #dateTimePicker1, testr_ud = #dt, testr_pd = #dt COMMIT";
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Parameters.AddWithValue("#dateTimePicker1",this.dateTimePicker1.Value.Date);
command.Parameters.AddWithValue("#textBox1", this.textBox1.Text);
command.Parameters.AddWithValue("#comboBox1",this.comboBox1.SelectedItem);
command.Parameters.AddWithValue("#testr_status",SqlDbType.VarChar);
command.Parameters.AddWithValue("#dt", dt);
int iResult = command.ExecuteNonQuery();
if (iResult > 0)
MessageBox.Show("Successfully saved ", "Error",MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Record not saved ", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
command.ExecuteNonQuery();
connection.Dispose();
command.Dispose();
Try cleaning up a bit your query or paste it on SSMS and declare your parameters and you will figure out what is wrong.
In your case your INSERT statement has some errors.
This is not valid syntax VALUES (test_name = #combobox1) instead you only pass the parameter VALUES (#combobox1)
There are more columns in the INSERT statement than values specified in the VALUES clause, you are not providing a value for apte_name. In the c# code you will need to add that parameter too.
You are missing the closing parenthesis for the VALUES clause
You should end up with something like this (not tested)
string selectQuery =
#"BEGIN TRANSACTION
UPDATE tester SET
test_ad = #dateTimePicker1,
test_ud = #dt,
test_pd = #dt
WHERE test_name = #textBox1;
INSERT INTO records
(
testr_status,
testr_name,
testr_ad,
testr_ud,
testr_pd,
apte_name
)
VALUES
(
#testr_status,
#comboBox1,
#dateTimePicker1,
#dt,
#dt,
#apte_name
);
COMMIT";
The actual problem is, that is one big, invalid SQL statement. Use the semi-colon to separate statements, like so:
"BEGIN TRANSACTION;
INSERT ...;
UPDATE ...;
ETC ...;
COMMIT;"
That said, don't embed transaction statements in a query string. Do what Oliver suggests in another answer.
You can use SqlTransaction
using (SqlConnection conn = new SqlConnection("Connection String"))
{
conn.Open();
SqlTransaction trans;
trans = conn.BeginTransaction();
string selectQuery = "your sql query";
SqlCommand command = new SqlCommand(selectQuery, connection);
int iResult = command.ExecuteNonQuery();
if (iResult > 0)
{
trans.Commit();
}else{
trans.Rollback();
}
conn.Close();
}
Use a formatted string for your select query by using # and the syntax in the value block in not accurate.
string selectQuery = #"
BEGIN TRANSACTION
UPDATE tester SET test_ad = #dateTimePicker1, test_ud = #dt, test_pd = #dt WHERE test_name = #textBox1;
INSERT INTO records(testr_status, testr_name, testr_ad, testr_ud, testr_pd, apte_name) VALUES(#testr_status, #comboBox1, #dateTimePicker1, #dt, #dt);
COMMIT";
I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error.
"Data type mismatch in criteria expression."
i'm sure it's something with the ' x ' i put in my query but still can't figure out what is THE problem.
it's (int,int,string,string,string,int,int,string,int,int) format
string SqlStr = string.Format("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values({0},{1},'{2}','{3}','{4}',{5},{6},'{7}',{8},{9})", s.ClientId,s.OrderId,s.Date,s.CardTyp,s.PayMethod,s.Ex_Y,s.Ex_M,s.CcComp,s.CcNum,s.TotalSale);
Thanks for your help.
String.Format will not be a good approach for building queries. I suggest you to use, Parameterised queries that helps you to specify the type too and also its more helpful to prevent injection: Here is an example for you:
string query = "insert into Orders" +
"(client_id,order_id,date_,card_typ,...)" +
" values(#client_id,#order_id,#date_,#card_typ...)";
using (SqlCommand sqCmd = new SqlCommand(query, con))
{
con.Open();
sqCmd.Parameters.Add("#client_id", SqlDbType.Int).Value = s.ClientId;
sqCmd.Parameters.Add("#order_id", SqlDbType.VarChar).Value = s.OrderId;
sqCmd.Parameters.Add("#date_", SqlDbType.DateTime).Value = s.Date;
sqCmd.Parameters.Add("#card_typ", SqlDbType.Bit).Value = s.CardTyp;
// add rest of parameters
//Execute the commands here
}
Note: I have included only few columns in the example, you can replace ... with rest of columns.
Please dont use a concatenation string ...
Here is an example :
using (SqlConnection connection = new SqlConnection("...connection string ..."))
{
SqlCommand command = new SqlCommand("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values(#client_id,#order_id,#date_,#card_typ,#pay_mthd,#ex_y,#ex_m,#cc_comp,#cc_num,#t_sale)", connection);
SqlParameter pclient_id = new SqlParameter("#client_id", System.Data.SqlDbType.Int);
pclient_id.Value = 12;
command.Parameters.Add(pclient_id);
SqlParameter pcard_typ = new SqlParameter("#card_typ", System.Data.SqlDbType.VarChar);
pcard_typ.Value = "some value";
command.Parameters.Add(pcard_typ);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
I keep getting a 'data type mismatch in criteria expression' when trying to insert into my Access 2010 table. The table has field names of:
GradeKey - AutoNumber,
Grade - Text,
Comments - Text,
TellerNum - Number,
TestName - Text.
The TestName is also a foreign key from another table. Any ideas on what I need to use to fix the data type mismatch?
using (OleDbConnection con = new OleDbConnection(constring))
{
try
{
string cmdstring = "INSERT INTO GRADE (Grade, Comments, TellerNum, TestName) VALUES (#grade, #comments, #teller, #test)";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#teller", OleDbType.Integer).Value = comboBox5.Text;
cmd.Parameters.AddWithValue("#grade", OleDbType.Char).Value = textBox7.Text;
cmd.Parameters.AddWithValue("#comments", OleDbType.Char).Value = textBox10.Text;
cmd.Parameters.AddWithValue("#test", OleDbType.Char).Value = comboBox16.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
OleDbType.Integer should be an integer.Try parsing comboBox5.Text to int:
cmd.Parameters.AddWithValue("#teller", OleDbType.Integer).Value = int.Parse(comboBox5.Text);
OleDb does not support named parameters. It only supports positional parameters. You need to add your parameters in the same order as they appear in the query:
cmd.Parameters.AddWithValue("#grade", OleDbType.Char).Value = textBox7.Text;
cmd.Parameters.AddWithValue("#comments", OleDbType.Char).Value = textBox10.Text;
cmd.Parameters.AddWithValue("#teller", OleDbType.Integer).Value = comboBox5.Text;
cmd.Parameters.AddWithValue("#test", OleDbType.Char).Value = comboBox16.Text;
Here is my code that I thought worked but it continues to give me a syntax error in my FROM clause. Could someone help me understand what I am missing? Without the try\catch, it highlights the line int result = (int)cmd.ExecuteScalar();.
string constring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jwhite\Documents\TrainingDB.accdb";
string cmdText = "SELECT COUNT(*) FROM USER WHERE Username=#p1 AND [Password]=#p2";
using (OleDbConnection con = new OleDbConnection(constring))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
try
{
con.Open();
cmd.Parameters.AddWithValue("#p1", textBox1.Text);
cmd.Parameters.AddWithValue("#p2", textBox2.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
groupBox1.Visible = false;
groupBox2.Visible = true;
string commandText = "SELECT RIGHTS FROM USER WHERE Username=#p1 and [Password]=#p2";
using (OleDbCommand command = new OleDbCommand(commandText, con))
{
command.Parameters.AddWithValue("#p1", textBox1.Text);
command.Parameters.AddWithValue("#p2", textBox2.Text);
string query = (string)command.ExecuteScalar();
{
if (query == "Administrator")
{
toolStripMenuItem59.Enabled = true;
administratorToolStripMenuItem1.Enabled = true;
administratorToolStripMenuItem3.Enabled = true;
administratorToolStripMenuItem4.Enabled = true;
administratorToolStripMenuItem5.Enabled = true;
administratorToolStripMenuItem2.Enabled = true;
administratorToolStripMenuItem6.Enabled = true;
toolStripMenuItem92.Enabled = true;
toolStripMenuItem108.Enabled = true;
}
}
}
}
else
MessageBox.Show("Invalid Credentials, Please Try Again");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
Instead of USER write [USER] as USER is a reserved word.
See List of Reserved Words HERE
According to http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx OleDbCommand does not support named parameter
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
So order of parameter is important.
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
using (var conexao = Conexao())
{
conexao.Open();
string rotaloja = Convert.ToString(dtExcel.Rows[i][1]) + Convert.ToString(dtExcel.Rows[i][0]);
string bn = "select * from Emb where ROTALOJ= #rotaloja";
OleDbCommand cmd1 = new OleDbCommand(bn, conexao);
cmd1.Parameters.AddWithValue("#rotaloja", rotaloja);
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
using (OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read())
{
try
{
string cmdText = "UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja";
conexao.Open();
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
try
{
string cmdText = "INSERT INTO Emb (ROTALOJ , ROTA, LOJA, QTDEEMBAL) VALUES (#rotaloja,#p0,#p1,#p2)";
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
//////////////////////////////////////////////////////////////////////////////////////////////
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
}
}
I am doing import excel to database more when he does select to see if you have the information in the database is giving error can be? for those who help me thank you
Img : http://i.stack.imgur.com/qxQDm.png
You created a new query Queryyy and assumed that the parameters attached with previous query cmd1 would be available with your command string bn. You need to add parameter to your query Queryyy
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Query.Parameters.AddWithValue("#rotaloja", rotaloja); //here
using (OleDbDataReader drr = Queryyy.ExecuteReader())
//.......rest of your code
}
Consider using helpful variable names.
In your current code, you added parameter to a cmd1 which is independent of Queryyy. In your new query Queryyy, you are using command text which requires a parameter and since you are not passing it, you are getting the exception.
Take a look at : OleDbCommand.Parameters Property, You may have to pass the parameter with ?, since it doesn't seem to support named parameters.
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
You're not setting the value of #rotaloja in this query:
"UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja"
OleDBCommand does not support names parameters. Replace your parameters with ? in each SQL statement and add the parameters in the order that they appear in the query.