I have found many posts on here which are relating to my issue however I am struggling to find out what exactly I need to change to solve my problem of updating an MS Access database from a C# application. So I apologize if people feel this post is too similar to others. Here is my update code:
private void button1_Click(object sender, EventArgs e)
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ts\Documents\testDB.accdb");
using (OleDbConnection conn = new OleDbConnection (ConnString))
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "UPDATE [Table4] SET [EmpName] = ?, [Age] = ?, [Mobile] = ? WHERE [ID] = ?";
cmd.Parameters.AddWithValue("#ID", OleDbType.VarChar).Value = idtextBox1.Text;
cmd.Parameters.AddWithValue("#EmpName", OleDbType.VarChar).Value = nametextBox2.Text;
cmd.Parameters.AddWithValue("#Age", OleDbType.VarChar).Value = agetextBox3.Text;
cmd.Parameters.AddWithValue("#Mobile", OleDbType.VarChar).Value = mobiletextBox4.Text;
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
Form1_Load(sender, e);
MessageBox.Show("record updated ");
}
}
For OleDb the order of parameters is of paramount importance. The reason your update will not work, is that you are supplying the ID parameter first, whereas in your SQL it is last (comes in the WHERE clause). Move this parameter to the end and it should work.
The revised code should be something like this:
private void button1_Click(object sender, EventArgs e)
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ts\Documents\testDB.accdb");
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "UPDATE [Table4] SET [EmpName] = ?, [Age] = ?, [Mobile] = ? WHERE [ID] = ?";
cmd.Parameters.AddWithValue("#EmpName", OleDbType.VarChar).Value = nametextBox2.Text;
cmd.Parameters.AddWithValue("#Age", OleDbType.VarChar).Value = agetextBox3.Text;
cmd.Parameters.AddWithValue("#Mobile", OleDbType.VarChar).Value = mobiletextBox4.Text;
cmd.Parameters.AddWithValue("#ID", OleDbType.VarChar).Value = idtextBox1.Text;
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
}
Form1_Load(sender, e);
MessageBox.Show("record updated ");
}
I have made a couple of other minor changes, most importantly moving the Form1_Load and the MessageBox outside of the using block. In general you should keep code within using blocks to a minimum, so that the resources can be freed as soon as possible. I also removed the Close(). The OleDbConnection's destructor automatically calls Close(), so there is no specific need to call it yourself.
One other thing might be wrong. You have the ID as a varchar. Are you sure about this? It would be more usual if it were an integer. In which case, you would need to parse the idTextBox1.Text to an integer with int.Parse(), or safer with int.TryParse(), and change the parameter type as well.
Related
I have tried using methods that others have used here to fix their issue but none of them are working for me. I am new to the ASP.NET framework and cannot understand why the information I am trying to send to my database isn't working. Also, Visual Studios isn't giving em an error until I try to submit the new data which makes it difficult for me to pinpoint the problem.
namespace ylena_exercise
{
public partial class KnockoutBind : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=ylena_exercise;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
GridView1.Visible = false;
}
protected void AddBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Customers ('"+numid.Text+"','"+txtcustomer.Text+"','"+txtcontact.Text+"','"+txtaddress.Text+"','"+txtcity.Text+"','"+numpostcode.Text+"','"+txtcountry.Text+"')",con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
Label1.Visible = true;
Label1.Text = "Data Stored Successfully!";
numid.Text = "";
txtcustomer.Text = "";
txtcontact.Text = "";
txtaddress.Text = "";
txtcity.Text = "";
numpostcode.Text = "";
txtcountry.Text = "";
}
}
}
Is there something wrong with my data? Or perhaps the issue is ExecuteNonQuery?
You missed Values in your insert statement your code should be like this:
SqlCommand cmd = new SqlCommand("insert into Customers values('"+numid.Text+"',....
Also you should always use parameterized queries to avoid SQL Injection:
SqlCommand cmd = new SqlCommand("insert into Customers values(#numid,...");
cmd.Parameters.AddWithValue("#numid",numid.Text);
Include column names in your sql and set the values like this:
var command = "insert into customers (id, name, contact, address, city, postcode, country) values (#id, #name, #contact, #address, #city, #postcode, #country)";
SqlCommand cmd = new SqlCommand(command);
cmd.Parameters.AddWithValue("#id", numid.Text);
cmd.Parameters.AddWithValue("#name", txtcustomer.Text);
cmd.Parameters.AddWithValue("#contact", txtcontact.Text);
cmd.Parameters.AddWithValue("#address", txtaddress.Text);
cmd.Parameters.AddWithValue("#city", txtcity.Text);
cmd.Parameters.AddWithValue("#postcode", numpostcode.Text);
cmd.Parameters.AddWithValue("#country", txtcountry.Text);
cmd.ExecuteNonQuery();
[Courtesy: Soner Gönül & user2946329]
Hey so I managed to figure out why ExecuteNonQuery was giving me issues. It turns out I simply did not match the table columns names with the variables in the SQL command.
Sorry for all of the trouble guys! Nevertheless, I appreciate all of the helpful suggestions and advice.
I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.
I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}
i'm trying to use an insert method in my studentHelperClass, I am trying to activate it on a button click on my form, I don't know how to make it work with a text box, so if someone could help with that, that would be great.
This is my method:
public static void insertStudent()
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (#personID)";
cmd.Parameters.AddWithValue("#personID", "123345667788");
prevID(conn, cmd);
}
and this is my form:
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent();
}
EDIT:
private static void prevID(MySqlConnection conn, MySqlCommand cmd)
{
conn.Open();
cmd.ExecuteNonQuery();
long studentNumber = (long)cmd.LastInsertedId;
Console.Write("previous id {0} ", studentNumber);
Console.ReadLine();
conn.Close();
}
Considering the information, assuming that your prevId(conn,cmd) is calling ExecuteNonQuery, you will still need to set the cmd.CommandText to be equal to your myInsertSql (as other answers have pointed out).
To answer your question though,
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(studentIdTextBox.Text);
}
public static void insertStudent(string studentId)
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (?personID)";
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("?personID", studentId);
prevID(conn, cmd);
}
Ive also assumed your studentId is a string. If the database has it as a bigint, you will have to do the proper long.TryParse() call.
You need to set cmd.CommandText as myInsertSQL
and also need to call cmd.ExecuteNonQuery()
string sql = "INSERT INTO person (personID) VALUES (#personID)";
using (MySqlConnection conn = connection())
using (MySqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
}
You must assign your string variable, 'myInsertSQL' to cmd.CommandText, and then call, cmd.ExecuteNonQuery();
I.e.
cmd.CommandText = myInsertSQL;
cmd.ExecuteNonQuery();
cmd.Dispose();
Always call 'Dispose();' when finished so the .net Garbage Collection can cleanup and manage resources.
You don't use the myInsertSQL string at all, you just set it. You have to set the string as the command text by cmd.CommandText = myInsertSQL and you have to call the method cmd.ExecuteNonQuery().
I have a gridview that has and auto- generated delete button. The grid has one datakeyname and for some reason it I am getting this error : Message: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I have looked at many tutorials and examples. This code should work right?
protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from t_run_schedule_lots " +
"where rec_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = rec_id ;
cmd.CommandType = CommandType.Text;
cmd.Connection = this.sqlConnection1;
this.sqlConnection1.Open();
//execute insert statement
cmd.ExecuteNonQuery();
this.sqlConnection1.Close();
//re-populate grid */
fill_grid();
grdBins.EditIndex = -1;
grdBins.DataBind();
// this bit was just to see if I was capturing the ID field properly.
lblBins.Visible = true;
lblBins.Text = rec_id.ToString();
}
If anyone knows a good example in C# that would make this work it would be greatly appreciated.
I might be misunderstanding your question but according to here the EditIndex property is zero-based so you can't set it to -1. Setting it to that value will throw an ArgumentOutOfRangeException.
Here is what I did to get it working:
GridViewRow row = (GridViewRow)grdBins.Rows[e.RowIndex];
Label id = (Label)row.FindControl("Label9");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from t_run_schedule_lots " +
"where rec_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(id.Text) ;
Although I don't know why the RowIndex option would not work. Anyway it is working now.
Sounds like you don't have the DataKeyNames="rec_id" in the gridview aspx set?
cant get to datakeys if you haven't let the page know what they are
this is a refactored version of your code.
protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(connectionString)){
conn.Open();
string cmdText = #"delete from t_run_schedule_lots
where rec_id = #id";
using (SqlCommand cmd = new SqlCommand(cmdText, conn)){
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", rec_id);
cmd.ExecuteNonQuery();
}
}
grd.EditIndex = -1;
fill_grid();
grdBins.DataBind();
}