Unable to insert data in MS Access using parameterized query in c# - c#

I have the following code which tries to store e values form 3 textboxes into a MS Access 2007 database.
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\dxs.accdb");
string SqlString = "Insert Into tests( [Nam], [add], [phone]) Values (?,?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(#"Nam", textBox1.Text);
cmd.Parameters.AddWithValue(#"add", textBox2.Text);
cmd.Parameters.AddWithValue(#"phone",textBox3.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("entered");
}
}
But even though the code is correct after entering values nothing is being stored in table.

Shouldn't
cmd.Parameters.AddWithValue(#"Nam", textBox1.Text);
Be:
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
And so on for the other parameters?

When i had the similar problems, solution was:
If database is part of application it can be copied in a bin folder - and then application work with it. That is why you can`t find your changes in datatables with MS Access client.

Make sure your database exists in output(bin) folder where exists your exe file of project. If not then copy it there. After your have your database file at right place, You will be to see the changes.
Additionally, you also need few changes in your code, you have problem with your parameter.
Change Values (?,?,?) to Values (#Nam,#add,#phone)"; and #"Nam" to "#Nam". See the comments Correction1 and Correction2.
Also no need to use double slash \\ when you are using # at beginning of string
string ConnString=#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\dxs.accdb");
string sql="Insert Into tests([Nam],[add],[phone]) Values (#Nam,#add,#phone)";
// Correction 1: Above line is changed ?,?,? to parameter names (names used by your command)
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
cmd.Parameters.AddWithValue("#add", textBox2.Text);
cmd.Parameters.AddWithValue("#phone",textBox3.Text);
// Correction 2: your parameter names are changed #"xyz" to "#xyz"
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("entered");
}
}

your insert statement should be like dis
string SqlString = "Insert Into tests( [Nam], [add], [phone]) Values (#Nam, #add, #phone)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
cmd.Parameters.AddWithValue("#add", textBox2.Text);
cmd.Parameters.AddWithValue("#phone",textBox3.Text);
try this

Related

Inserting value into database

I wanted to insert values into database but it is not working eventhough my code perfectly working when its used as stored procedure. I am trieng to use button click to store the value. Please tell whats wrong with the code. Its not showing any error or exception but data is not getting updated in the table
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES ('12', 'abcd', '20')";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
my columns acnum and shares_bought are "int" and scripname is
"varchar"
Then you will not need single quotes for your integer values. Use it as;
...VALUES (12, 'abcd', 20)"
A few things more;
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
You don't need cmd.CommandType = CommandType.Text line. It is .Text by default.
var conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
using(var sqlConnection1 = new SqlConnection(conStr))
using(var cmd = sqlConnection1.CreateCommand())
{
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES (12, 'abcd', 20)";
sqlConnection1.Open();
cmd.ExecuteNonQuery();
}
Set breakpoint in code and see if code is executing. In case you don't know how to, see here.
As you are not getting any exception on insert statement and it's not reflecting in database, either you have different connection string or your code is not getting executed.

hebrew from the Connection

I am trying with oracle database to Insert and select Hebrew letters
and it not working well.
I tried
Insert into mytable values ('היי');
and the result is ??? and not היי
can someone help me with that
Edit:
Now after i ask from DBA for hebrew option i can write in Hebrew from the sqlplus
but now from my project it still write ???
my code is
OleDbConnection conn = Connect();
conn.Open();
OleDbCommand com = new OleDbCommand("Insert into mytable values ('היי')", conn);
com.ExecuteNonQuery();
and still the result is ???
I can't really test this because I don't know anything about your database (not even your column names), but you should do that command with parameters:
var testString = "היי"; // Do be aware that Visual Studio displays Hebrew text right-to-left, so the actual string is reversed from what you see.
using (OleDbConnection conn = Connect())
{
conn.Open();
using (OleDbCommand com = conn.CreateCommand())
{
// OleDbCommand com = new OleDbCommand("Insert into mytable values ('היי')", conn);
com.CommandText = "Insert into mytable values (?)";
com.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar }).Value = testString;
com.ExecuteNonQuery();
}
}
Also, don't forget to dispose your disposables via a using statement.
Relatedly, here is a report that using a parameterized query fixed a similar problem with OracleCommand.

Adding to database using Oledb Syntax error in INSERT INTO statement

when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?
protected void btnAddBook_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (#Title, #Author, #Price, #Edition)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#Author", TextBox2.Text);
cmd.Parameters.AddWithValue("#Price", TextBox3.Text);
cmd.Parameters.AddWithValue("#Edition", TextBox4.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.
You could try to force the AddWithValue to create a numeric parameter with
cmd.Parameters.AddWithValue("#Price", Convert.ToDecimal(TextBox3.Text));
(Of course assuming a decimal Price column)
Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.

inserted values on updated database are not correct - MVC

im trying to update the values of columns from the same row in my database.
Here is my code:
if (ModelState.IsValid)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd = cn.CreateCommand();
cmd.CommandText = #"Update Content Set Des='#Des', Sc='#Sc' Where ID_Img=#Id_Img";
cmd.Parameters.Add("#Des", SqlDbType.VarChar);
cmd.Parameters["#Des"].Value = model.Des;
cmd.Parameters.Add("#Sc", SqlDbType.VarChar);
cmd.Parameters["#Sc"].Value = model.Sc;
cmd.Parameters.Add("#Id_Img", SqlDbType.Int);
cmd.Parameters["#Id_Img"].Value = model.Id_Img;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
the code works and i get no error, but when i check in my database the values inserted are #Desc and #Sc and not properly the values which comes from form in my view.
I have set a breakpoint and check which values are in the variables all off them have the correct one..
What im doing wrong?
Someone can give me a hand pls?
Don't wrap your parameters in quotes in the actual query. Try this:
cmd.CommandText = #"Update Content Set Des=#Des, Sc=#Sc Where ID_Img=#Id_Img";
The parameters are smart enough to know if they need to be wrapped in quotes or not based on their data types.

How do I insert the auto-increment ID into a MySQL table using MySQL ODBC with ASP.Net/C#?

I am using MySQL ODBC to insert data into a MySQL table. The first column in the table is an ID that is of type int and auto increments. When I insert the data for the very first row, what should the value be for #ReqID, as shown below? Also, how do I ensure that subsequent executions are auto incrementing for the ID?
Here is the C#:
string conString = WebConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
using (OdbcCommand cmd = con.CreateCommand()) {
cmd.CommandText = "INSERT INTO GraphicsRequest (RequestID, Graphic1Desc, Graphic2Desc, Graphic3Desc, ColorChart, Hex1, Hex2, Hex3, Hex4) VALUES (#reqID, #g1d, #g2d, #g3d, #colorChart, #hex1, #hex2, #hex3, #hex4)";
cmd.Parameters.AddWithValue("#reqID", 1);
cmd.Parameters.AddWithValue("#g1d", txtGraphic1Desc.Text);
cmd.Parameters.AddWithValue("#g2d", txtGraphic2Desc.Text);
cmd.Parameters.AddWithValue("#g3d", txtGraphic3Desc.Text);
cmd.Parameters.AddWithValue("#colorChart", ddlColorChart.SelectedValue);
cmd.Parameters.AddWithValue("#hex1", lblColor1.Text);
cmd.Parameters.AddWithValue("#hex2", lblColor2.Text);
cmd.Parameters.AddWithValue("#hex3", lblColor3.Text);
cmd.Parameters.AddWithValue("#hex4", lblColor4.Text);
cmd.ExecuteNonQuery();
}
}
In MySQL you shouldn't supply the ID-field during an INSERT if you want to use the auto incrementing feature of the database itself.
So that would be in your case.
string conString = WebConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
using (OdbcCommand cmd = con.CreateCommand()) {
cmd.CommandText = "INSERT INTO GraphicsRequest (Graphic1Desc, Graphic2Desc, Graphic3Desc, ColorChart, Hex1, Hex2, Hex3, Hex4) VALUES (#g1d, #g2d, #g3d, #colorChart, #hex1, #hex2, #hex3, #hex4)";
cmd.Parameters.AddWithValue("#g1d", txtGraphic1Desc.Text);
cmd.Parameters.AddWithValue("#g2d", txtGraphic2Desc.Text);
cmd.Parameters.AddWithValue("#g3d", txtGraphic3Desc.Text);
cmd.Parameters.AddWithValue("#colorChart", ddlColorChart.SelectedValue);
cmd.Parameters.AddWithValue("#hex1", lblColor1.Text);
cmd.Parameters.AddWithValue("#hex2", lblColor2.Text);
cmd.Parameters.AddWithValue("#hex3", lblColor3.Text);
cmd.Parameters.AddWithValue("#hex4", lblColor4.Text);
cmd.ExecuteNonQuery();
}
}
This way the database will INSERT a new row with the next available the ID for you.
Since the other have answered your question, I would suggest that you use the MySQL Connector in your project instead of using OLEDB objects. Download and install the MySQL Connector and then add a reference in your project to the MySQL.Data extension and then add the MySql.Data.MySqlClient using statement to your class and then update your code as follows:
string conString = WebConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
using(MySqlConnection con = new MySqlConnection(connectionString))
{
con.Open();
using(MySqlCommand cmd = new MySqlCommand()
{
cmd.Connection = con; //<-- It looks like you are missing this line in your code
cmd.CommandText = "INSERT INTO GraphicsRequest (Graphic1Desc, Graphic2Desc, Graphic3Desc, ColorChart, Hex1, Hex2, Hex3, Hex4) VALUES (#g1d, #g2d, #g3d, #colorChart, #hex1, #hex2, #hex3, #hex4)";
cmd.Parameters.AddWithValue("#g1d", txtGraphic1Desc.Text);
cmd.Parameters.AddWithValue("#g2d", txtGraphic2Desc.Text);
cmd.Parameters.AddWithValue("#g3d", txtGraphic3Desc.Text);
cmd.Parameters.AddWithValue("#colorChart", ddlColorChart.SelectedValue);
cmd.Parameters.AddWithValue("#hex1", lblColor1.Text);
cmd.Parameters.AddWithValue("#hex2", lblColor2.Text);
cmd.Parameters.AddWithValue("#hex3", lblColor3.Text);
cmd.Parameters.AddWithValue("#hex4", lblColor4.Text);
cmd.ExecuteNonQuery();
}
}
probably this would solve the problem .
strong textcom.ExecuteNonQuery();
long id = com.LastInsertedId;

Categories