i am using asp.net with C# as code behind
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='"+TextBox1.Text+"',inst_code='"+DropDownList1.SelectedItem+"',ms_oms='"+Label7.Text+"',elligiblity='"+Label12.Text+"',Board='"+DropDownList5.SelectedItem+"',percentage='"+TextBox4.Text+"' WHERE elg_id = '"+DropDownList4.SelectedItem+"'";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
i am getting error on
cmd.ExecuteNonQuery();
that Data type mismatch in criteria expression.
Don't code like
string connection_string="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False";
using(OleDbConnection cn = new OleDbConnection(connection_string))
{
cn.Open();
string sql = "UPDATE main SET s_name=?,inst_code=?,ms_oms=?,elligiblity=?,Board=?,percentage=?,amount=? WHERE elg_id =?";
using(OleDbCommand cmd = new OleDbCommand(sql, cn))
{
cmd.Parameters.Add(new OleDbParameter("s_name",TextBox1.Text.Trim()));
cmd.Parameters.Add(new OleDbParameter("inst_code",DropDownList1.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("ms_oms",Label7.Text.ToString()));
cmd.Parameters.Add(new OleDbParameter("elligiblity",Label12.Text));
cmd.Parameters.Add(new OleDbParameter("Board",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("percentage",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter(amount",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("elg_id",DropDownList5.SelectedItem.Value.ToString()));
cmd.ExecuteNonQuery();
cn.Close();
}
}
Response.Write("alert('DATA UPDATED')");
Remove single quotes around DropDownList4.SelectedItem. I bet your elg_id column is of type integer or something, and you're giving it a string.
Having that said, you would be really better off if you provided text of error, database table structure and maybe some other information so that people wouldn't have to read your mind.
Can you try DropDownList1.SelectedItem.Text or DropDownList1.SelectedItem.Value
This should be the same for all DropDownLists.
Also you might have to convert TextBox4 to the appropriate datatype for "percentage".
Assuming that the percentage is a Double, you'd need something like
Double.Parse(Textbox4.Text)
Lastly, if you're not sending a "string" to the query, you would be really good to remove the single quotes from those fields. That way you're not parsing the data but still sending string information.
this is de correct code
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='" + TextBox1.Text + "',inst_code='" + DropDownList1.SelectedItem.Value.ToString() + "',ms_oms='" + Label7.Text + "',elligiblity='" + Label12.Text + "',Board='" + DropDownList5.SelectedItem.Value.ToString() + "',percentage='" + float.Parse(TextBox4.Text) + "',amount='" + Label10.Text + "' WHERE elg_id = " + DropDownList4.SelectedItem.Value + "";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
thanxx
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='" + TextBox1.Text + "',inst_code='" + DropDownList1.SelectedItem.Value.ToString() + "',ms_oms='" + Label7.Text + "',elligiblity='" + Label12.Text + "',Board='" + DropDownList5.SelectedItem.Value.ToString() + "',percentage='" + float.Parse(TextBox4.Text) + "',amount='" + Label10.Text + "' WHERE elg_id = " + DropDownList4.SelectedItem.Value + "";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
Related
I wrote the query for inserting data to MySQL table "Persons":
SqlConnection con = new SqlConnection();
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
But it's not working. I have one connection for the whole database, but it's not working for a specific table. How I can create a connection between specific table to query in C#?
What is it? SqlConnection con = new SqlConnection() you need to pass a connection string which comprises DBname, username, pasword, server name ... etc; you are not passing those information anywhere then how can you expect it to connect to your database without having the information.
Pass the connection string either in constructor or using the property.
SqlConnection con = new SqlConnection(connection_string)
(OR)
SqlConnection con = new SqlConnection();
con.ConnectionString = connection_string;
There are different ways to insert data into the tables. I suggest to use parametrized sql query to keep safe from malicious occurrence.
Firstly you should have a ConnectionString something like this:
string connectionString = "Persist Security Info=False;User ID=UserName;Password=YourPassword;Server=ServerName";
And than:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TableName (Col1, Col2, ColN) VALUES (#Col1, #Col2, #ColN)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Col1", txtName.Text);
cmd.Parameters.AddWithValue("#Col2", txtPhone.Text);
cmd.Parameters.AddWithValue("#ColN", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Try this code. Please edit your credentials before trying.
Replace localhost with SQL server instance name, user id with your MySQL server instance user id, password with your MySQL server instance password and testdb with your database name. It should work fine.
string connectionString = #"server=localhost;user id=admin;password=admin;database=testdb;";
SqlConnection con = new SqlConnection(connectionString);
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
I managed to create my own "save, update, delete" program with SQL after watching a video.
I have an issue, if I click "update" without having the "IndexNumber" in the database, nothing will happen.
Can anybody advise me on how to improve my "update" button? Perhaps if the data does not exist, the program can prompt the user with a message box instead of doing nothing. Like "IndexNumber does not exist therefore unable to update"
My update code
SqlConnection con = new SqlConnection(
#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath +
"\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"UPDATE GlennTeoStudents SET IndexNumber = '" +
numIN.Value + "',Name = '" + txtName.Text + "',Age ='" + txtAge.Text +
"',HandPhoneNumber = '" + txtHP.Text + "',GPA = '" + numGPA.Value +
"' WHERE (IndexNumber='" + numIN.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
SqlCommand.ExecuteNonQuery() returns the number of rows affected (int).
You could check on the return value:
SqlCommand.ExecuteNonQuery(asd)
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (!(rowsAffected > 0))
{
throw new ArgumentException(<Your Message>);
}
Then just catch the exception wherever you call the method and display your messagebox with
MessageBox.Show(<Your Message>)
try
{
.....
con.Open();
SqlCommand cmd = new SqlCommand(#"Select count(*) from GlennTeoStudents
WHERE (IndexNumber='" + numIN.Value + "')", con);
int count1 = cmd.ExecuteScalar();
if (count1 != 0)
{
do your update
}
else
{
give your message box
}
}
I get error
INCORRECT SYNTAX NEAR ' '
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection=conn;
cmd.CommandText = "update student set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli'" + textBox5.Text + "',Tavalod'" + maskedTextBox1.Text + "',Address'" + richTextBox1.Text + "',Madraak'" + textBox7.Text + "',Shahriye'" + textBox8.Text + "',Mobile'" + textBox6.Text + "'where Name=" + textBox1.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
My database is SQL Server Express.
There are some errors:
missing equals after: CodeMeli=, Tavalod=, Address=, Madraak=, Shahriye=, Mobile=
missing ending of the sql statement + "'"
This will work:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = "update student set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli='" + textBox5.Text + "',Tavalod='" + maskedTextBox1.Text + "',Address='" + richTextBox1.Text + "',Madraak='" + textBox7.Text + "',Shahriye='" + textBox8.Text + "',Mobile='" + textBox6.Text + "'where Name='" + textBox1.Text + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
In any case, I recommend you the use of Parameters. Why?
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd= new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = #"UPDATE Student SET Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile WHERE Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
using table2 instead of student
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = "update table2 set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli='" + textBox5.Text + "',Tavalod='" + maskedTextBox1.Text + "',Address='" + richTextBox1.Text + "',Madraak='" + textBox7.Text + "',Shahriye='" + textBox8.Text + "',Mobile='" + textBox6.Text + "'where Name='" + textBox1.Text + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
OR
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd= new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = #"UPDATE table2 SET Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile WHERE Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection=conn;
cmd.CommandText = #"
UPDATE
Student
SET
Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,
Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile
WHERE
Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
Here is the code. First Format your query properly, your query was unreadable. Second use Command parameters to avoid SQL Injection. You can read in Wikipedia about sql injection. Third write "nice" textBox ID, which have some meaning.
Look at your CommandText. There are some Parameters without ( = )
Format like this :
cmd.CommandText = "update student set Name='" + textBox1.Text + "',
Family='" + textBox2.Text + "',
Fathername='" + textBox3.Text + "',
ShenasName='" + textBox4.Text + "',
CodeMeli='" + textBox5.Text + "',
Tavalod='" + maskedTextBox1.Text + "',
Address='" + richTextBox1.Text + "',
Madraak='" + textBox7.Text + "',
Shahriye='" + textBox8.Text + "',
Mobile='" + textBox6.Text + "'
where Name=" + textBox1.Text;
Incorrect syntax ')'
private void btnInsert_Click(object sender, EventArgs e) {
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Customers(Id,Name,Country,) values (#Id,#Name,#Country)",con);
con.Open();
cmd.Parameters.AddWithValue("#Id",dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name",dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Country",dataGridView1.Rows[i].Cells[2].Value);
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Added successfully!");
}
I have created a sql server database in godaddy and created a table named property manually.i also successfuly connected my application to the database using connection string.But i am unable to insert any values to the table using my c# code
Below is my C# code
string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',#data,#data2,#data3,#data4);";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("#data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("#data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
Parameterize your query and clean it up a bit. Hope this helps.
using (SqlConnection con = new SqlConnection("Connection Info"))
{
// Create your parameterized command.
SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
" image1, image2, image3, image4) VALUES " +
" (#name, #email, #phone, #heading, #description, #location, " +
" ,#image1,#image2,#image3,#image4)", con);
using (cmd)
{
// Set your command type.
cmd.CommandType = CommandType.Text;
// Add your parameters.
cmd.Parameters.AddWithValue("#name", "nameParamHere");
cmd.Parameters.AddWithValue("#email", "emailParamHere");
// and so on until you complete all params.
// Execute your command.
using (SqlDataReader dr = cmd.ExecuteReader()) { };
}
}
Try granting insert to your connection string "USER ID". See this link for more info...
http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm
GRANT INSERT
ON [property]
TO {user_name}
[WITH GRANT OPTION];
I had make this small method to insert data from C# forms into my Oracle database. The code processed fine, but when I go to SQL Developer to check if the record has been inserted or not, I found nothing...
public void conn2db()
{
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statmentcmd = "insert into register_user (userid,username,pass,fullname,phonenum,gender,country) values (" + 1 + "," + textBox1.Text + "," + textBox2.Text + "," + textBox4.Text + "," + textBox5.Text + "," + radioButtonValue+ ","+comboBox1.Text+");";
OracleConnection conn = new OracleConnection(connstring);
conn.Open();
MessageBox.Show("connected to database");
OracleCommand cmd = new OracleCommand();
cmd.CommandText=statmentcmd;
cmd.Connection=conn;
OracleDataAdapter oda = new OracleDataAdapter(cmd);
MessageBox.Show(statmentcmd);
conn.Close();
MessageBox.Show("Connection closed");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try executing the command like this:
OracleCommand cmd = new OracleCommand();
cmd.CommandText = statmentcmd;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
Or more simply:
OracleCommand cmd = new OracleCommand(statmentcmd, conn);
cmd.ExecuteNonQuery();
try change the Copy to Output Directory : Do notcopy