This is my first step to programming.guys your help hands required.I watched youtube video & write small program,the exact way he written..he doesn't have error.but i got the error.I just passed the textbox values database.(error is database table definition wrong ). In my table i use for this field is BBMgrID nvarchar(50) NOT NULL
SqlConnection con = new SqlConnection("Data Source=spilap;Initial Catalog=spiDB;User ID=sa;Password=sa123");
protected void btn_submit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tbl_BBmgr values('" + TextBox1.Text+"')",con);
cmd.ExecuteNonQuery();
}
Try this :
SqlCommand cmd = new SqlCommand("Insert [TableName] ([ColumnName]) Values(#A)", con);
cmd.Parameters.AddWithValue("#A", TextBox1.text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Update :
SqlCommand cmd = new SqlCommand("Insert [TableName] ([Column1],[Column2],[Column3]) Values(#A,#B,#C)", con);
cmd.Parameters.AddWithValue("#A", TextBox1.text);
cmd.Parameters.AddWithValue("#B", TextBox2.text);
cmd.Parameters.AddWithValue("#C", TextBox3.text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You should write it like this:
Insert into tbl_BBmgr (BBMgrID) values('" + TextBox1.Text+"')
If like you stated you have 5 fields in the DB table, you need to explicitly specify the column you want the value to go:
SqlCommand cmd = new SqlCommand("Insert into tbl_BBmgr (BBMgrID) values('" + TextBox1.Text+"')",con);
EDIT: Now and in the future, to ensure that you are sending the right value to the respective field, its always advisable to specify the columns in your INSERT statement in the form:
INSERT INTO Name_Of_Table ([Column1], [Column2], [Column3], ...) VALUES ([Value_For_Column1], [Value_For_Column2], [Value_For_Column3], ...)
Related
I faced syntax error in UPDATE statement, while updating password in Access database in C#:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE into userdata(password)values('"+TextBox1.Text+"') where id=#id";
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
}
It's because your SQL Query is not correct, that's not how you update data in your database. It should be like this:
query = "Update [tableName] SET [ColumnName] = 'Values', [ColumnName1] = 'Values2',...";
You should learn at least the basics of SQL syntax, more information here
And also, you shouldn't concatenate your query since it will become vulnerable for SQL Injection attack, you should at least use Parameterized Query
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE yourTableName SET [yourColumnName] = #YourFirstValue, [secondColumnName] = #YourSecondValue WHERE [columnKey] = #ID"
cmd.Parameters.AddWithValue("#YourFirstValues", textbox1.Text);
cmd.Parameters.AddWithValue("#YourSecondValue ", textbox2.Text);
cmd.Parameters.AddWithValue("#ID", textbox3.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
you have to fix your query
"UPDATE userdata SET password=#password where id=#id";
and add new lines before cmd.ExecuteNonQuery()
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
I had a similar problem, it gave me a syntax error that I solved by checking the whole string and actually there was a comma too many, I don't know if this answer of mine can be useful, among other things after some time.
protected void addItem_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string PID;
Button oButton = (Button)sender;
PID = oButton.CommandArgument.ToString();
int productId = Convert.ToInt32(PID);
Debug.Write(productId);
string email = (string)(Session["email"]);
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
When my query executes, I get an error
Invalid column name 'productId'
As you can see, I have converted a string into an integer variable, I have printed off the variable to check what it is returning. It does return a int as expected, but for some odd reason i can not insert into to my table. Any help would be great.
Hope productId is not the primary key of the basket table.
Then,instead of
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
Modify like below
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( #productId,#email)", con);
cmd.Parameters.Add(new SqlParameter("#productId",productId );
cmd.Parameters.Add(new SqlParameter("#email",email );
Why suggested to modify is to avoid SQLInjection attack. If you are unaware about that please go through the below link and learn it
https://en.wikipedia.org/wiki/SQL_injection
Two issues here, number 1, and a big one, parameterize that query! You're opening yourself up to SQL injection attacks with code like that.
The second is that you're not actually passing in your productId variable, you're telling it to use the value for the productId column - which is also the column you're trying to insert into.
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values (#productId, #email)");
cmd.Parameters.AddWithValue("#productId", productId);
cmd.Parameters.AddWithValue("#email", email);
I can't stress enough how dangerous it is to dump user input into SQL that's going to be run directly on your database.
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(#Id, #Name, #Age, #Contact No, #Address", con);
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
sc.Parameters.AddWithValue("#Contact No", textBox3.Text);
sc.Parameters.AddWithValue("#Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
con.Close();
}
You are making a lot of errors here.
First, you have 6 fields in your table and, if you don't give a list
of fields when you make an insert query, then you should add values
for all 6 fields.
Second you have 5 parameters placeholders but you add only 4
parameters and this is another exception.
Last but not least the syntax of the insert statement is formally
wrong because there is no closing parenthesys
So, let's try to fix at the best of our knowledge
string cmdText = #"INSERT INTO Patient_Details
(ID, Name, Age, Gender, [Contact No], Address)
VALUES(#Id,#Name,#Age,#Gender,#ContactNo, #Address)"
using (SqlConnection con = new SqlConnection(....))
{
con.Open();
SqlCommand sc = new SqlCommand(cmdText, con);
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
// For the following two fields, add a value or remove
// the parameters and fix the query text above....
sc.Parameters.AddWithValue("#age", ????);
sc.Parameters.AddWithValue("#gender", ????);
sc.Parameters.AddWithValue("#ContactNo", textBox3.Text);
sc.Parameters.AddWithValue("#Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
Like Sankar Raj pointed out you missed the a ) in the Insert query and a parameter #Age to add.Using space in parameter #Contact No is also not allowed.
You have used using for SqlConnection.I suggest you use the same for SqlCommand also, then you don't need to explicitly Dispose it. And again it seems you are not using try catch that's you were not able to identity the problem.
SUGGESTED CODE
try{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
using (SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(#Id, #Name, #Age,#Gender, #ContactNo, #Address)", con)){
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
sc.Parameters.AddWithValue("#Gender", textBox3.Text);
sc.Parameters.AddWithValue("#ContactNo", textBox4.Text);
sc.Parameters.AddWithValue("#Age", textBox5.Text);
sc.Parameters.AddWithValue("#Address", textBox6.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
Note: I've removed con.Close(). Since you are using using statement it will automatically Close & Dispose the Connection and release the resources it uses.
I have code like this:
con.Open();
cmd = new SqlCommand("insert into Penawaran (ID_Paket,Jenis_Paket,Harga_Paket) Values (#ID_Paket,#Jenis_Paket,#Harga_Paket", con);
cmd.Parameters.AddWithValue("#ID_Paket", txtIDPaket.Text);
cmd.Parameters.AddWithValue("#Jenis_Paket", txtjenisPaket.Text);
cmd.Parameters.AddWithValue("#Harga_Paket", txtHargaPaket.Value); // this is int sir how to insert it, still error i write like this
cmd.ExecuteNonQuery();
con.Close();
Please help me to inside int to my table Paket.
There is a missing parenthesis at the end of Insert query
INSERT INTO Penawaran (ID_Paket,Jenis_Paket,Harga_Paket)
VALUES (#ID_Paket,#Jenis_Paket,#Harga_Paket) --Here
Try this
SqlConnection con = new SqlConnection();
con.Open();
SqlCommand cmd = new SqlCommand("insert into Penawaran (ID_Paket,Jenis_Paket,Harga_Paket) Values (#ID_Paket,#Jenis_Paket,#Harga_Paket", con));
cmd.Parameters.Add("#ID_Paket", SqlDbType.Int);
cmd.Parameters.Add("#Jenis_Paket", SqlDbType.VarChar);
cmd.Parameters.Add("#Harga_Paket", SqlDbType.VarChar); // this is int sir how to insert it, still error i write like this
cmd.Parameters["#ID_Paket"] = int.Parse(txtIDPaket.Text);
cmd.Parameters["#Jenis_Paket"] = txtjenisPaket.Text;
cmd.Parameters["#Harga_Paket"] = txtHargaPaket.Value; // this is int sir how to insert it, still error i write like this
cmd.ExecuteNonQuery();
con.Close();
I'm trying to increment an integer in an MS Access table from a c# .net page during insert.
I'm getting a syntax error when attempting the following. Also unsure if I should be using an ExecuteNonQuery() or not?
OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You miss a bracket after tblTarget:
OleDbCommand cmd =
new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);
Here is a little review of your code, try using the using pattern:
using(var conn = new Connection())
{
conn.Open();
string sql = "INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}
You're missing a bracket, try:
INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))
But I think you are going to have other issues, you need something closer to this:
INSERT INTO tblTarget ( target, ref )
SELECT #target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY #target;
The correct way to achieve your goal is
string sql = "INSERT INTO tblTarget (target,ref) " +
"SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
I would not do the increment by the sql or code, we can use AutoNumber data type for auto increase the value in access.
string sql = "INSERT INTO tblTarget(target) VALUES(#target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}