access MDB update data in C# via sql - c#

I've had help here
Inserting and Updating data to MDB
but still have a problem with update
I have an access mdb file with table "Table1" and 3 colums
ID
INFO
TEXT
I can add new info, find info but the update gives me an unknown error. Something is wrong with the command I sent.
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Table1 SET Info = #Info, text = #text WHERE ID = #ID;";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
int numAffected = cmd.ExecuteNonQuery();
con.Close();

The OleDbCommand does not support named parameters. This:
"UPDATE Table1 SET Info = #Info, text = #text WHERE ID = #ID;";
is equivalent to this:
"UPDATE Table1 SET Info = ?, text = ? WHERE ID = ?;";
and when you add parameters to the Parameters collection they are assigned in the order they are added. So the first parameter added will be assigned to the first placeholder, the second parameter to the second etc. You may use names for the placeholders for readability purposes but they do not matter when assigning values.
So you need to change the order in which you add the values to match the order in your query:
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
cmd.Parameters.AddWithValue("#ID", textBox1.Text);

Related

Trying to insert int variable into SQL Server table

protected void addItem_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string PID;
Button oButton = (Button)sender;
PID = oButton.CommandArgument.ToString();
int productId = Convert.ToInt32(PID);
Debug.Write(productId);
string email = (string)(Session["email"]);
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
When my query executes, I get an error
Invalid column name 'productId'
As you can see, I have converted a string into an integer variable, I have printed off the variable to check what it is returning. It does return a int as expected, but for some odd reason i can not insert into to my table. Any help would be great.
Hope productId is not the primary key of the basket table.
Then,instead of
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
Modify like below
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( #productId,#email)", con);
cmd.Parameters.Add(new SqlParameter("#productId",productId );
cmd.Parameters.Add(new SqlParameter("#email",email );
Why suggested to modify is to avoid SQLInjection attack. If you are unaware about that please go through the below link and learn it
https://en.wikipedia.org/wiki/SQL_injection
Two issues here, number 1, and a big one, parameterize that query! You're opening yourself up to SQL injection attacks with code like that.
The second is that you're not actually passing in your productId variable, you're telling it to use the value for the productId column - which is also the column you're trying to insert into.
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values (#productId, #email)");
cmd.Parameters.AddWithValue("#productId", productId);
cmd.Parameters.AddWithValue("#email", email);
I can't stress enough how dangerous it is to dump user input into SQL that's going to be run directly on your database.

Adding a Where Clause to a OleDbCommand

I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);

Exporting Data into Access using C# simultaneously into two tables

I'm trying to enter the id, first and last name into a table and then according to a combo box input I create another record right after that saves id of the student and the id of the Team which was chosen bu the combo box. Here is my code. everything runs well the only problem is that after that the record in the TeamPlayers table is not added. Please anyone ?!?
try
{
string team = null;
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO Students(BaruchID, FirstName, LastName) VALUES(#id, #first, #last)", conn);
conn.Open();
comm.Parameters.AddWithValue("#id", tbBaruchID.Text);
comm.Parameters.AddWithValue("#id", FirstName.Text);
comm.Parameters.AddWithValue("#id", LastName.Text);
comm.ExecuteNonQuery();
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("SELECT TeamNum FROM Teams WHERE TeamName='" + cbTeam.Text +"'", conn);
conn.Open();
OleDbDataReader dr = comm.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
team = dr["TeamNum"].ToString();
}
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO TeamPlayers(ID, BaruchID, TeamID) VALUES(#i, #id, #teamid)", conn);
conn.Open();
comm.Parameters.AddWithValue("#i", 1);
comm.Parameters.AddWithValue("#id", tbBaruchID.Text);
comm.Parameters.AddWithValue("#teamid", int.Parse(team));
conn.Close();
}
MessageBox.Show("Student Added for team"+ cbTeam.Text);
}
The parameter names in the first INSERT statement are not used when adding the parameter values. All the comm.Parameters.AddWithValue("#id", .....); lines use #id. Therefore, the actual id value is never saved to table student.
The second INSERT has always uses 1 as the value of 'id'. Assuming that 'id' is a primary key, it can only contain unique values. Make the 'id' field an IDENTITY field and then remove it from the INSERT statement. Each time a record is then added to the table it will be given the next number in an ever incrementing sequence.
Corrected Code: http://dotnetfiddle.net/Dr9842

loop through all values in sql table using sql data reader

I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is
if (!IsPostBack)
{
string username = Session["username"].ToString();
con.Open();
string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
SqlCommand cmd = new SqlCommand(strqryScript, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string name = rdr["teach_id"].ToString();
rdr.Close();
string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
classname.Text = rdr2["class_id"].ToString();
}
con.Close();
}
extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. any help please! and thanks ..
While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. This will overwrite the previous text and leave you with the name of the last teacher retrieved. You need to add to the previous text or use a List.
classname.Text += rdr2["class_id"].ToString();
Said that, let me point you to a big problem in your code. String concatenation is really bad when you build sql commands. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here
You should use parameterized queries like this (just for your first command)
string strqryScript = "select * from dbo.teachers where user_id = #id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("#id", username);
....
This is the issue you need to fix:
classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!
You need to make sure, you fill a list, a dataset or whatever, when reading the data!

Insert data into SQL Server from C# code

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query

Categories