ODBC must declare the scalar variable - c#

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

Related

INSERT INTO Syntax error C# access database

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

SQL visual studio command

i am trying to update a mysql database through visual studio
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set \""+col1+"\" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
when I run this and click the button it says I have a syntax error but I have not be able to find it. Can anyone point it out to me
You don't need quotes around the column col1:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set "+col1+" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
I would do it this way:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update npanxx set '"+ col1 +"'='" + newval1 + "' WHERE NPA_NXX= '" + val1 + "'", con);
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}

Local Database Insert query does nothing

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

Updating multiple tables using SqlDataAdapter

I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}

Object reference not set to an instance of an object. Please Help to solve error

I am new to C#.
Kindly tell me what`s wrong with this code. I am inserting data in data base using two input fields EndValueTextBox and StartValueTextBox .
I am receiving following error. "Object reference not set to an instance of an object"
private void buttonSave_Click(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
da = new SqlDataAdapter();
try
{
connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Connection String");
}
try
{
connection.Open();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
//SqlDataAdapter da = new SqlDataAdapter(query, connString);
da.InsertCommand.CommandText = sql;
da.InsertCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}
Your SqlDataAdapter is never assigned a connection to execute the query on. You need to associate the SqlConnection with the SqlDataAdapter during or after construction.
This line da.InsertCommand.CommandText = sql; has to be in that way:
da.InsertCommand = new SqlCommand(sql);
At what point you are the exception? Probably those line
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
SqlDataAdapter da = new SqlDataAdapter();
string connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
SqlConnection connection = new SqlConnection(connetionString);
try {
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Here's a minor rewrite of your code (not tested) that should take care of the SqlDataAdapter not having the connection object assigned and also demonstrates how to use parameterized queries to help defend against SQL Injection attacks:
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
// The using block will automatically dispose of your connection when
// the block is exited and is considered standard practice.
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";))
{
SqlDataAdpter da = new SqlDataAdapter();
connection.Open();
// Assign the SqlConnection object to the SqlDataAdapter
da.Connection = connection;
// Parameterize the query as shown below
string sql = "INSERT INTO TBLWORKERS(first_name, last_name) VALUES(#first_name, #last_name)";
da.InsertCommand.CommandText = sql;
// Add the values for the parameters
da.InsertCommand.Parameters.Add("#first_name", SqlDbType.NVarChar, 25, StartValueTextBox.Text);
da.InsertCommand.Parameters.Add("#last_name", SqlDbType.NVarChar, 25, EndValueTextBox.Text);
// Execute the query - rows will have the number of rows
// affected. should be 1 in this case if succesful
int rows = da.InsertCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}

Categories

Resources