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!");
}
}
Related
I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.
I am trying to edit an Access DB_. For some reason I cannot insert anything. I believe my code is correct. The connection string is correct (though for security purposes I put a fake one for this post). At the end, I do not get the MessageBox like I am supposed to at the end of the function. Nothing was added to the Access DB either.
Any reason why this might be?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}
Suggestion - please consider refactoring your code as follows, and step through it, a line at a time, in the MSVS debugger:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
If you wanted to use prepared statements, you'd change your code to something like this:
string sql = "insert into table1 values(#param1, #param2)";
...
cmd.Parameters.AddWithValue("#param1", textBox1.Text);
cmd.Parameters.AddWithValue("#param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
You can read more about techniques and guidelines for mitigating SQL injection here:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Here is another good article:
Best Practices for Using ADO.NET (MSDN)
update data in access database using name two column
because one column have same data because SerialNumber and Start can be Repeat
that's make update in all row have same data
i use this code but i have syntax Error
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Timer set Stop='" + label1.Text + "'where (SerialNumber,Start)='" + comboBox1.Text + "','" + textBox1.Text + "' ";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Data saved");
connection.Close();
send_data f2 = new send_data(comboBox1.Text,label2.Text);
f2.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("ERORR" + ex);
}
}
The correct syntax for the WHERE clause is
WHERE fieldname operator value AND/OR fieldname operator value ....
So the correct way to update that record is
string query = #"update Timer set Stop=? where SerialNumber = ? AND Start = ?";
command.CommandText = query;
command.Parameters.AddWithValue("#p1", label1.Text);
command.Parameters.AddWithValue("#p2", comboBox1.Text );
command.Parameters.AddWithValue("#p3", textBox1.Text);
command.ExecuteNonQuery();
Notice that before the WHERE keyword you need a space and I have changed your code to use a more secure parameterized approach instead of string concatenation
private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from mws.login_info where login_id='" + this.admin_id_textbox + "'and login_password1='" + this.admin_password_textbox1 + "' and login_password2='" + this.admin_password_textbox2 + "'");
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("username and password is correct");
}
else
MessageBox.Show("username and password not correct");
myConn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You have not associated the command with the connection. You code lacks of the following line
SelectCommand.Connection = myConn ;
Said that, imagine that I write in your admin_id_textbox the following text
' OR login_id like '%' --
what happen to your checks for the correct login?
It is called Sql Injection and it is a very dangerous situation for every kind of database access.
Use always a parameterized query to build sql commands, in particular when part of your command is built using user input text
private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"select * from mws.login_info
where login_id=#id and login_password1=#pwd
and login_password2=#pwd2";
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand SelectCommand = new MySqlCommand(cmdText, myConnection))
{
myConn.Open();
SelectCommand.Parameters.AddWithValue("#id", this.admin_id_textbox);
SelectCommand.Parameters.AddWithValue("#pwd",this.admin_password_textbox1);
SelectCommand.Parameters.AddWithValue("#pwd2",this.admin_password_textbox2);
using(MySqlDataReader myReader = SelectCommand.ExecuteReader())
{
if(myReader.HasRows)
MessageBox.Show("username and password is correct");
else
MessageBox.Show("username and password not correct");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
i have question. I want to store data on my mysqldatabase using this C#
private void btnSaveFilm_Click(object sender, EventArgs e)
{
try
{
MySqlConnection conn = new MySqlConnection(connection.mysqlconnectionbuilder());
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO film(judul,genre,asal,kondisi)"
+ "VALUES(#judul,#genre,#asal,#kondisi)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#judul", textBoxJudul.Text);
cmd.Parameters.AddWithValue("#genre", category(comboBoxGenre.SelectedValue.ToString()).ToString());
cmd.Parameters.AddWithValue("#asal", asal(comboBoxAsal.SelectedValue.ToString()).ToString());
cmd.Parameters.AddWithValue("#kondisi", checkedStatus());
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception exe)
{
Console.Write("Error on Save Film : " + exe.ToString() + "\n" +exe.Message);
}
}
but it shows error System.NullReferenceException: Object reference not set to an instance of an object.
Error at this line 40:
cmd.Parameters.AddWithValue("#genre",kategori(comboBoxGenre.SelectedValue.ToString()).ToString());
how to solve that?
refractor your code into this, use using statement,
string connString = connectionmysqlconnectionbuilder();
using (MySqlConnection conn = new MySqlConnection(connString)
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = #"INSERT INTO film(judul,genre,asal,kondisi)
VALUES(#judul,#genre,#asal,#kondisi)";
cmd.Parameters.AddWithValue("#judul", textBoxJudul.Text);
cmd.Parameters.AddWithValue("#genre", kategori(comboBoxGenre.Text).ToString());
cmd.Parameters.AddWithValue("#asal", asal(comboBoxAsal.Text).ToString());
cmd.Parameters.AddWithValue("#kondisi", checkedStatus());
try
{
comm.Open();
cmd.ExecuteNonQuery();
}
catch(MySqlException ex)
(
Console.WriteLine(ex.ToString());
)
}
}
you could also use
comboBoxGenre.Text instead of comboBoxGenre.SelectedValue
There can be two reasons:
1.comboBoxGenre.SelectedValue will be null
2.kategori() will be returning null
you can handle null error by using Convert.ToString() instead of variable.toString()
so use this instead also for other lines
cmd.Parameters.AddWithValue("#genre", Convert.ToString(kategori(Convert.ToString(comboBoxGenre.SelectedValue))));