Hi I've got a problem: My OleDbCommand not working.
Element of code:
private void Btn_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "insert into Account (Nick,Password) values ('" + NickEnter.Text + "', '" + PassEnter.Text + "');";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error! | " + ex, "Error!");
}
}
You are using reserved words for column names. You need to escape these using square brackets.
Also you should use parameters for your values. This guards against sql injection (where possible) and also ensures that a value with a single quote does not destroy the statement.
Finally I noticed you have a field named password and a plain text value, you should never store passwords as plain text. Instead store a 1 way hash of the password. There are many libraries out there you can use.
private void Btn_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "INSERT INTO [Account] ([Nick],[Password]) values (?,?);";
// note that order is critical here
command.Parameters.Add(new OleDbParameter("#nick", OleDbType.VarChar)).Value = NickEnter.Text;
command.Parameters.Add(new OleDbParameter("#password", OleDbType.VarChar)).Value = PassEnter.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error! | " + ex, "Error!");
}
}
I am using Access and my field userId's datatype is autonumber.
I'm getting a data type mismatch error and I'm not sure why. Here is my code.
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "delete from userdetail where userId='" + textBox1.Text + "'";
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
Pass the id as a number:
cmd.CommandText = "delete from userdetail where userId = " + textBox1.Text + "";
Trying to display a value from Access Database to display onto ListBox on a form. The previous form sends this form a string which is 'prevval'- for reference to the code. Not entirely sure what the issue is? Please Help!!
The QuestionID is technically a number but is it an issue if im making it a string because its being presented on the ListBox?
Error System.Data.OleDb.OleDbException (0x80040E10): No value given
for one or more required parameters
Code:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "SELECT QuestionID FROM tblQuestions WHERE (Topic='" + prevval + "')";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
listQuestions.Items.Add(reader.ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
Try this
listQuestions.Items.Add(reader["QuestionID"].ToString());
I am trying to save some data in a database using an INSERT query but it is saving double value on single click. For example I save 'Lahore', it'll save it two times:
Lahore
Lahore
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
if (dt.Read())
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}
Your code is doing exactly what you told it to.
If you call an Execute*() method twice, it will run your query twice.
It's saving twice because you are executing the query twice:
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
You are saving twice.
The executeNonQuery will return the number of rows affected so use this instead.
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
var rowsAffected = query.ExecuteNonQuery();
if (rowsAffected == 1)
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}
I have a ASP.NET Application and a MySQL Database. I want write a Class to insert,delete and show the Data from the database. I have a Connection to the Database but I can't insert data in the database.
My Class insert method:
public string CreateEntry(string Connectionstring, string mitarbeiter)
{
connection = new MySqlConnection(Connectionstring);
try
{
var command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
return "Mitarbeiter wurde angelegt";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
connection.Close();
}
}
The Connectionstring is correct. I don't get a error but there is no data in the database.
My tablename: tb_mitarbeiter
columns: ID and Vorname
You should simply execute the command
....
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
command.ExecuteNonQuery();
....
I suppose that mitarbeiter is the real value that should be set in the database.
If this is the case remember to use parameters to insert/update your data
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES (?name)";
command.Parameters.AddWithValue("?name", mitarbeiter);
connection.Open();
command.ExecuteNonQuery();
You forgot to execute the command by calling command.ExecuteNonQuery(). This is how I would typically do it:
public string CreateEntry(string connectionString, string valueToInsert)
{
var stringToReturn = "";
try
{
using(var connection = new MySqlConnection(connectionString))
{
//Open connection
connection.Open();
//Compose query using sql parameters
var sqlCommand = "INSERT INTO table_name (field_name) VALUES (#valueToInsert)";
//Create mysql command and pass sql query
using(var command = new MySqlCommand(sqlCommand, connection))
{
command.Parameters.AddWithValue("#valueToInsert", valueToInsert);
command.ExecuteNonQuery();
}
stringToReturn ="Success Message";
}
}
catch(exception ex)
{
stringToReturn = "Error Message: " + ex.Message;
}
return stringToReturn;
}
There are a few key things to keep in mind:
Wrap disposable objects with a using. In the case of
MySqlConnection, it will properly close and dispose the connection
when its out of scope.
Use SQL parameters when passing values inside
your query. This will avoid SQL injection and its much more easier
to maintain.
Personally, I like to have one exit point in a
function. In this example, the "stringToReturn" variable holds the
value to return once the function is done executing both
successfully or in case of a failure.
To do a Insert / Update / Delete u should add
connection.Open();
command.ExecuteNonQuery();
For select ()to show data from database use:
connection.Open();
command.ExecuteReader();
{
string MyConnection2 = "datasource=localhost;port=3306;username=root;password=1234";
string Query = "insert into DBname.TableName(id,Name,First_Name,Age,Address) values('" +this.IdTextBox.Text+ "','" +this.NameTextBox.Text+ "','" +this.FirstnameTextBox.Text+ "','" +this.AgeTextBox.Text+ "','" +this.AddressTextBox.Text+ "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not executing the command use SqlCommand.ExecuteNonQuery
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
command.ExecuteNonQuery();
return "Mitarbeiter wurde angelegt";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
connection.Close();
}
You missed to write this:-
....
connection.Open();
command.ExecuteNonQuery();
....
You can also used Sql parameter to prevent Sql Injection
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = #"INSERT INTO `tb_mitarbeiter` (`Vorname`) VALUES (#tom)";
command.Parameters.AddWithValue("#tom", tom);
connection.Open();
command.ExecuteNonQuery();
return "Mitarbeiter wurde angelegt";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
command.Dispose();
command.Close();
connection.Close();
}