i know this topic is already discuss many time, but i still dont get my problem solved..
ok, i have a form to insert registration data into MS Access Database (2007), but my code doesnt insert data into database, and there are no errors,
here is the code:
OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb");
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
private void btnSave_Click(object sender, EventArgs e)
{
string idCard = this.txtID.Text;
string name = this.txtName.Text;
DateTime dateBirth = this.dateEdit1.DateTime;
cn.Open();
cmd.CommandText = "Insert into tb_reg (id, name, dateBirth, blood_type) Values(#id,#name,#dateBirth)";
cmd.Parameters.AddWithValue("#id", idCard);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#dateBirth", dateBirth.ToString());
adapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Succesfully added");
else
MessageBox.Show("try again");
cn.Close();
}
the message box always show "successfully added".
I had something like this in a project of mine. Maybe it works for you:
string insertString = string.Format(CultureInfo.InvariantCulture, "INSERT INTO tb_reg VALUES ('{0}', '{1}', '{2}', {3})", idCard, name, dateBirth, blood_type);
OleDbCommand cmd = new OleDbCommand(insertString, new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb"));
cmd.Connection.Open();
int numberAdded = cmd.ExecuteNonQuery();
if (numberAdded < 1)
{
//do something, the data was not added
}
else
{
//be happy :)
}
cmd.Connection.Close();
As I said, that worked for me.
The OleDB provider does not support named parameters. Change your SQL to
cmd.CommandText = #"Insert into tb_reg (id, name, dateBirth, blood_type)
Values(?,?,?,?)";
You can name the parameters when you create them, but it will assign them to the ? placeholders in the order that they are added to the command.
Also note that you're missing a parameter for blood_type.
Whatever you do, DON'T change to use string concatenation. It open the door for SQL Injection attacks.
Related
I wrote an application with C# and MS Access. I have my form login which it works. OK. And I have an insert statement which does not throw any error, but everything I enter into my textbox doesn't get inserted into my database, and when I want to make an update, it returns the same as insert statement, I mean no error, but the row is not inserted or updated.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void validateaddmember_button_Click(object sender, EventArgs e)
{
addmember.Visible = false;
MemoryStream ms = new MemoryStream();
pictureBox4.Image.Save(ms, pictureBox4.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],[Password],[Function],[Role],[Registerdata],[Personaldescription],[Phonenumber],[Picture]) VALUES(#f,#l,#e,#p,#fu,#r,#reg,#per,#ph,#pic) ";
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#l", lastname_textbox.Text);
cmd.Parameters.AddWithValue("#e", email_textbox.Text);
cmd.Parameters.AddWithValue("#ph", phone_textbox.Text);
cmd.Parameters.AddWithValue("#fu", function_textbox.Text);
cmd.Parameters.AddWithValue("#r", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#per", richTextBox1.Text);
cmd.Parameters.AddWithValue("#p", repeatpassword_textbox.Text);
cmd.Parameters.AddWithValue("#pic", a);
cmd.ExecuteNonQuery();
con.Close();
}
And here I have in other form my update.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void bunifuFlatButton1_Click(object sender, EventArgs e)//login method
{
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText ="update [team] set [Numberoflogin] = [Numberoflogin] + 1 where [Email]=#LEMAIL";
cmd2.Parameters.AddWithValue("#LEMAIL", materialSingleLineTextField1.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
Along with marc_s's important note -- you switched phone and password, make sure you fix that -- you only need # in the sql string. So not
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
but
cmd.Parameters.AddWithValue("Firstname", firstname_textbox.Text);
Use the field name (Firstname). #f is just a marker. With Access, you could write the sql string like so:
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],
[Password],[Function],[Role],[Registerdata],[Personaldescription],
[Phonenumber],[Picture]) VALUES(?,?,?,?,?,?,?,?,?,?)";
so when you add the parameter value, use the field name.
You could also open the connection right before cmd.ExecuteNonQuery();, like your update form.
I'm trying to connect to database file "crepeDB.accdb"
When I added it through data connection, and works fine when I drag any table to appear as data grid in any form but when I try to connect to the database to insert data it gives me this error:
An unhandled exception of type 'System.NotImplementedException' occurred in Additional information: The method or operation is not implemented.
The code I'm using is as follows:
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;");
conn.Open();
string query = "insert into Sales (Sdate,SQuantity) values ('" + dateTimePicker1.Value + "','" + textBox9.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
This is the last thing I need to do in my project, would really appreciate any help.
Do not pass values for your fields concatenating them to form your command, instead use parameters.
int quantity;
if(!Int32.TryParse(textBox9.Text, out quantity))
MessageBox.Show("Invalid number");
else
{
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"insert into Sales (Sdate,SQuantity)
values (#date, #qta)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("#date", OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#qta", OleDbType.Integer).Value = quantity;
cmd.ExecuteNonQuery();
}
}
This is better because you don't ask someone else to convert your values from a string to the correct datatype. This automatic conversion (in particular with dates) is well know to cause problems when there is some kind of mismatch between the passed string and how the database engine interprets this string
N.B I am assuming the Sdate is a field of type DateTime and SQuantity is a field of type Integer in MS-Access. If not then you can change the OleDbType Int32.TryParse to the correct matching type
It is basically like this . . .
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();
Good day! I need help please..
This is my code on c# whenever I execute it nothing happens no error or hint
string myConnection = " datasource=localhost;port=3306;username=root;password=wolf";
string Query = " UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate='" + txtToBeReturned.Text + "' WHERE bikeID='" + txtBikeIdRent.Text + "'";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(Query, myConn);
myConn.Open();
MessageBox.Show("Data Saved");
myConn.Close();
I am not sure why the Upate won't work but when I execute this code on MySql
UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate=NOW() WHERE bikeID='2';
It works just fine can someone help me?
A command should be executed to do anything. Your code misses the call to SelectCommand.ExecuteNonQuery() line after the open connection. However after fixing this trivial error you could encounter other problems with the values concatenated to form your command text. What if the user types an invalid date? Have you ever heard of Sql Injection hacks?
This is how your code should be written after adding validation to your inputs and parameters to send values to your database
int bikeID = 0;
if(!Int32.TryParse(txtBikeIdRent.Text, out bikeID)
{
MessageBox.Show("Invalid number");
return;
}
DateTime returnDate;
if(!DateTime.TryParse(txtToBeReturned.Text , out returnDate)
{
MessageBox.Show("Invalid date");
return;
}
string myConnection = ".....";
string Query = #"UPDATE bikerentaldb.tblbikes
SET status='Rented', renteddate=NOW(),
assignedreturndate=#date
WHERE bikeID=#id";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand cmd = new MySqlCommand(Query, myConn))
{
myConn.Open();
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = returnDate;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = bikeID;
int rowUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
else
MessageBox.Show("No record match");
}
I've been looking into How to check user id already exists to see how to do this.
I am trying to get this working in my code, however it's not working. I don't get errors or something, but it just write data in database even if order number already exists.
The function:
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
cmd.Parameters.Add(param);
//sqlCommand.Connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
reader.Close();
}
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}
Sorry for this kinda well known and duplicated question, but for some reason I can't get it working.
You called the wrong command, change
SqlDataReader reader = sqlCommand.ExecuteReader();
to
SqlDataReader reader = cmd.ExecuteReader();
The problem is here:
SqlDataReader reader = sqlCommand.ExecuteReader();
You should execute the other command first
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
The latter command, when will be executed will tell you if there is any record in the testtabel table. If there is, then you should show the message:
Order already exist
Otherwise, you will execute your first command, that will insert the rows.
By the way, please try to avoid string concatenation, when you write sql queries. It is one of the most well known security holes. You code is open to SQL injections. You could use parameterized queries:
String query = "INSERT INTO testtabel (knaam, korder) VALUES (#knaam, #korder)";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
sqlCommand.Parameters.Add(new SqlParamete("#knaam",knaamTextBox.Text));
sqlCommand.Parameters.Add(new SqlParamete("#korder",kordernrTextBox.Text));
While your code is full of problems (magic pushbutton, SQL injections, absence of usings), there is main one. The approach you want to implement will fail on concurrent inserts, and must not be used.
Imagine, that two users run this code against the same database, using the same korder value:
1st executes SELECT - record with the given value doesn't exist;
2nd executes SELECT - record with the given value doesn't exist;
1st executes INSERT - record with the given value does exist;
2nd executes INSERT - ooops... we have a duplicate;
To avoid duplicates you must use unique indexes in database. Do not rely on your code.
You check HasRows for INSERT INTO testtabel bla...bla..bla.. not for `elect * from testtabel where korder'
Maybe you can use this (it comes from my head and not compiled, please adjust it with your own case)
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
//sqlCommand.Connection.Open();
SqlDataReader cmdReader = sqlCommand.ExecuteReader();
if (cmdReader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
cmdReader.Close();
}
SqlDataReader reader = sqlCommand.ExecuteReader();
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}
After spending several hours i am unable to figure out that why null values are being inserted into mySQL table using ASP.NET web page. I am using odbc connector for this.Below is the code for the same.
public int Insert(string FirstName, string LastName, int age)
{
OdbcConnection conn = new OdbcConnection(connStr);
conn.Open();
OdbcCommand odcmd_Insert = new OdbcCommand("INSERT INTO webuse(firstName,lastName,age) VALUES(#param1,#param2,#param3)",conn);
odcmd_Insert.Connection = conn;
odcmd_Insert.CommandType = System.Data.CommandType.Text;
try
{
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param1", FirstName));
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param2", LastName));
odcmd_Insert.Parameters.Add( new OdbcParameter("#param3", age));
return odcmd_Insert.ExecuteNonQuery();
}
catch (OdbcException e)
{
throw;
}
finally {
odcmd_Insert.Dispose();
conn.Close();
conn.Dispose();
}
}
I have debugged the code and all things seems well but all columns are updated with null values. Please help i am a noob to ASP.NET.
Please try your argument like as below. I have used the MySqlConnection. you can use ODBC connection as well.
try
{
// Connection string for a typical local MySQL installation
string cnnString = "Server=localhost;Port=3306;Database=ci_series;Uid=root;Pwd=";
// Create a connection object
MySqlConnection connection = new MySqlConnection(cnnString);
// Create a SQL command object
string cmdText = "INSERT INTO webuse(firstName,lastName,age) VALUES(?param1,?param2,?param3)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?param1", MySqlDbType.VarChar).Value = firstName;
cmd.Parameters.Add("?param2", MySqlDbType.VarChar).Value = lastName;
cmd.Parameters.Add("?param3", MySqlDbType.VarChar).Value = age;
connection.Open();
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
The command should be as
string cmdText = "INSERT INTO webuse(firstName,lastName,age) VALUES(?param1,?param2,?param3)";
I think that your OdbcCommand should be (replace in query #paramN with ?)
OdbcCommand odcmd_Insert = new OdbcCommand("INSERT INTO webuse(firstName,lastName,age) VALUES(?,?,?)",conn);
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param1", FirstName));
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param2", LastName));
odcmd_Insert.Parameters.Add( new OdbcParameter("#param3", age));
Instead of the parameter it takes a ? in the CommandText (leave the name in the actual parameters param1,param2,param3)