con.Open();
cmd = new OleDbCommand("insert into login (user, password) values ('" +textBox1 .Text + "','" + textBox2 .Text + "');",con);
cmd.CommandType = CommandType.Text;
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Record Successfuly Added");
}
else
{
MessageBox.Show("Record Fail to Added");
}
con.Close();
when i try to insert some of error appear ( syntax error in INSERT STATEMENT )
i'm try different method to values like Parameters or direct
plz !
Escape reserved keyword user
use parameterized query
avoid sql injection
Make use of disposable objects
Try this approach:
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(
"insert into login ([user], [password]) values (#user, #pass);",
con))
{
cmd.Parameters.Add(new OleDbParameter("#user", textBox1.Text ));
cmd.Parameters.Add(new OleDbParameter("#pass", textBox1.Text ));
if (temp > 0)
{
textBox1.Text = String.Empty;
textBox2.Text = String.Empty;
MessageBox.Show("Record Successfuly Added");
}
else
{
MessageBox.Show("Record Fail to Added");
}
}
}
Related
I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.
I'm getting data from another database the first connection is from con and the second database is DB_Student. I want to get the signature from DB_Student and put it into DB_Attendance which is con.
SqlCommand cmd = new SqlCommand();
cmd = con.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
con.Open();
cmd.CommandType = CommandType.Text;
string Query = "INSERT INTO TBL_Attendance(Signature) SELECT
Signature FROM DB_Students.TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "'";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Please Delete the row without name.");
}
This is just a simple way of registering new account credentials. My problem is that whenever I click the save button, the data will be saved twice in the database.
Sample image of the double entry in the database.
using (SqlConnection con = new SqlConnection(conString))
{
try
{
string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (#name,#pos,#username,#password)");
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pos", textBox4.Text);
cmd.Parameters.AddWithValue("#username", textBox2.Text);
cmd.Parameters.AddWithValue("#password", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
//MessageBox.Show(result.ToString());
// Check Error
if (result > 0)
MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You're calling ExecuteNonQuery() twice.
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
you excecute the query twice.
change:
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
to
con.Open();
int result = cmd.ExecuteNonQuery();
I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want
Consider the code below:
string ConnectionString = "dsn=mysql;uid=sa;DATABASE=userdb;";
string qryStr = "insert into info(code) values(#code);";
OdbcConnection con = new OdbcConnection(ConnectionString);
OdbcCommand cmd = new OdbcCommand(qryStr,con );
cmd.Parameters.Add("#code", System.Data.Odbc.OdbcType.Int).Value = "999";
cmd.Connection.Open();
OdbcDataReader odbcdtr = cmd.ExecuteReader();//exception "must declare the scalar variable #code"
con.Close;
This code is raising exception "must declare scalar vairable #code".
I'll be very grateful if anyone can point out the mistake that is in the code above.
I've finally found the solution as given in this link.
The Odbc interface does not recognise the use of #named variables, only ? which are taken by position. You can use ?Param1, ?Param 2 for readability, but the position is all that is used.
Try
string ConnectionString = "dsn=mysql;uid=sa;DATABASE=userdb;";
string qryStr = "insert into info(code) values(?code);";
OdbcConnection con = new OdbcConnection(ConnectionString);
OdbcCommand cmd = new OdbcCommand(qryStr,con );
cmd.Parameters.Add("#code", System.Data.Odbc.OdbcType.Int).Value = 999;
cmd.Connection.Open();
OdbcDataReader odbcdtr = cmd.ExecuteReader();
con.Close;
Worked 100% please try this
byte[] imageDatas = ReadFile(strFn);
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
OdbcCommand cmd = new OdbcCommand("insert into students(id,name,img) values(" + txtId.Text + ",'" + txtName.Text + "',?)", con);
cmd.Parameters.AddWithValue("#img", imageDatas);
cmd.ExecuteNonQuery();
MessageBox.Show("inserted successfully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}