When executing this query with parameters added as values, i get an error saying my syntax is wrong. I tried following multiple tutorials, looking up questions here is stack overflow, and when comparing, they seem the same, but mine does not seem to work.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\\Users\\fidyc\\OneDrive\\Desktop\\ProgrII.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT Product_Orders(order_ID,plankCount,thickness,width,height)VALUES(#order_ID, #plankCount, #thickness, #width, #height)");
cmd.Parameters.Add("#order_ID", OleDbType.Integer).Value = orderID;
cmd.Parameters.Add("#plankCount", OleDbType.Decimal).Value = plankCount;
cmd.Parameters.Add("#thickness", OleDbType.Decimal).Value = thickness;
cmd.Parameters.Add("#width", OleDbType.Decimal).Value = width;
cmd.Parameters.Add("#height", OleDbType.Decimal).Value = height;
cmd.Connection = con;
con.Open();
if (con.State == ConnectionState.Open)
{
/*try
{*/
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
/*}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
con.Close();
}*/
}
Edit: values are passed to the function
public static void Push(int orderID, decimal plankCount, decimal thickness, decimal width, decimal height)
{
The problem turned out to be the count column name, as sql has a count command, it needs to be
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,[count],thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
instead of
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,count,thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO bookRated "+
"([firstName], [lastName]) "+
"VALUES(#firstName, #lastName)";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#firstName", firstName),
new OleDbParameter("#lastName", lastName),
});
cmd.ExecuteNonQuery();
}
Related
IWhat i wanna do
So I tried this code
but it coudnt get a connection with the Database. I the connection string is correct
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into [kunde]Vorname()values(#nm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Connection = con;
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "insert into [kunde]Nachname()values(#nmm)";
cmdd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmdd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.
try
{
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tableName(column1,column2) values(#nm,#nmm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.ToString());
}
Hello I have a database with drivers and a combobox which is populated with the drivers. But when I add a new driver with a button Add Driver, it's added only in Microsoft Access table, not in the combobox. And once I reload the program, the new driver is deleted from the database. I also have connected the database in Data Source and I can edit the tables only from there(if I want to edit the combobox).
This is my connection with the database
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
cmd = new OleDbCommand();
con.Open();
cmd.Connection = con;
string query = "SELECT Name FROM Drivers";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboDriver.Items.Add(reader["Name"]);
}
con.Close();
and this is my Add Driver button:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
String Id = textID.Text;
String Name = textName.Text;
String Age = textAge.Text;
String City = textCity.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Drivers (Id, Name, Age, City) Values(#Id, #Name, #Age, #City)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Id", OleDbType.VarChar).Value = Id;
cmd.Parameters.Add("#Name", OleDbType.VarChar).Value = Name;
cmd.Parameters.Add("#Age", OleDbType.VarChar).Value = Age;
cmd.Parameters.Add("#City", OleDbType.VarChar).Value = City;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("New Driver Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
Just because you've added it to your database, doesn't mean anything else will happen.
You still need to update your UI.
Add this in after you have executed the query:
comboDriver.Items.Add(Name);
As an aside, you should also wrap the conn.Open() in a try catch as well
I am trying to insert a row into the database. Below is my query:
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
string query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.AddWithValue("#x", insert[2]);
command.Parameters.AddWithValue("#y", insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
conn.Close();
}
}
When I run it nothing happens (Also no SQL errors). What am I doing wrong? I am sorry if this is a stupid question, I am merely a beginner.
This should work (I have tested this with a select query that does work).
Have you tried storing the query on a stored procedure and calling it from C#? ... Thats actually easier than making the query via hard code inside the C# code ... Just create a stored procedure that does whatever you want it to do, then call it from C# and add the parameters. It should look something like this:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conection_String_s_Name"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.Your_Stored_Procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Input_Param_1", SqlDbType.VarChar, 18).Value = "C#_Parameter1";
cmd.Parameters.Add("#Input_Param_2", SqlDbType.VarChar, 45).Value = "C#Parameter_2";
cmd.Parameters.Add("#Input_Param_3", SqlDbType.VarChar, 45).Value = "C#Parameter_3";
cmd.Parameters.Add("#Input_Param_4", SqlDbType.Text).Value = "C#Parameter_4";
cmd.Parameters.Add("#Input_Param_5", SqlDbType.VarChar, 45).Value = "C#Parameter_5";
cmd.Parameters.Add("#Output_Parameter_1", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#Output_Parameter_2", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
"C#Output_Parameter_1" = "" + cmd.Parameters["#Output_Parameter_1"].Value;
"C#Output_Parameter_2" = "" + cmd.Parameters["#Output_Parameter_2"].Value;
Hope it helps.
My guess is that you have a type mismatch
If x, y are not int then substitute in the correct type
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
using (SqlCommand command = SqlCommand.CreateCommand())
{
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
command.Query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.Add("#x", SqlDbType.Int);
command.Parameters["#x"].Value = Int32.Parse(insert[2]);
command.Parameters.Add("#y", SqlDbType.Int);
command.Parameters["#y"].Value = Int32.Parse(insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
rowsRet = command.ExecuteNonQuery();
Console.WriteLine(rowsRet.ToString());
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
// op claims the insert is gone the next time the programs is run
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
}
}
Actually my code was suppose to check that is there any value in the course_choice_teacher table. If there is not, then it will insert some values into the table. Now this time there is no value in the table. So dr2.Read() should return false and do the else portion. But it is doing the reverse thing. I'll be very happy if you help me in this purpose.
string oradb = "Data Source=localhost;User Id=system;Password=cse;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd2 = new OracleCommand();
cmd2.Connection = conn;
cmd2.CommandText = "select * from course_choice_teacher where teacher_id='"+teacher_home.st+"' and choice_no=1";
cmd2.CommandType = CommandType.Text;
OracleDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
MessageBox.Show("Already Given");
}
else
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into course_choice_teacher values('" + teacher_home.st + "','" + dataGridView1.CurrentRow.Cells["course_id"].Value.ToString() + "',1)";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
}
conn.Dispose();
The datareader has property .HasRows to check if the result has some rows. This would be a proper way to check what you intend to do.
if (dr2.HasRows)
{
MessageBox.Show("Already Given");
}
else
{
.........
}
Consider the code below:
string ConnectionString = "dsn=mysql;uid=sa;DATABASE=userdb;";
string qryStr = "insert into info(code) values(#code);";
OdbcConnection con = new OdbcConnection(ConnectionString);
OdbcCommand cmd = new OdbcCommand(qryStr,con );
cmd.Parameters.Add("#code", System.Data.Odbc.OdbcType.Int).Value = "999";
cmd.Connection.Open();
OdbcDataReader odbcdtr = cmd.ExecuteReader();//exception "must declare the scalar variable #code"
con.Close;
This code is raising exception "must declare scalar vairable #code".
I'll be very grateful if anyone can point out the mistake that is in the code above.
I've finally found the solution as given in this link.
The Odbc interface does not recognise the use of #named variables, only ? which are taken by position. You can use ?Param1, ?Param 2 for readability, but the position is all that is used.
Try
string ConnectionString = "dsn=mysql;uid=sa;DATABASE=userdb;";
string qryStr = "insert into info(code) values(?code);";
OdbcConnection con = new OdbcConnection(ConnectionString);
OdbcCommand cmd = new OdbcCommand(qryStr,con );
cmd.Parameters.Add("#code", System.Data.Odbc.OdbcType.Int).Value = 999;
cmd.Connection.Open();
OdbcDataReader odbcdtr = cmd.ExecuteReader();
con.Close;
Worked 100% please try this
byte[] imageDatas = ReadFile(strFn);
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
OdbcCommand cmd = new OdbcCommand("insert into students(id,name,img) values(" + txtId.Text + ",'" + txtName.Text + "',?)", con);
cmd.Parameters.AddWithValue("#img", imageDatas);
cmd.ExecuteNonQuery();
MessageBox.Show("inserted successfully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}