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.
Related
Can anyone tell me what is the proper syntax code in using datetimepicker that would be saved directly to my Microsoft sql 2005? I'm using visual studio 2008 c#.
Here is my code:
private void button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
SqlDataAdapter dad = new SqlDataAdapter();
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
dateTimePicker1.Format = DateTimePickerFormat.Short;
string dateStr = Convert.ToString(dateTimePicker1.Text);
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro", conn);
dad.InsertCommand.Parameters.Add("#School_Name", SqlDbType.VarChar).Value = textBox1.Text;
dad.InsertCommand.Parameters.Add("#Province", SqlDbType.VarChar).Value = comboBox1.Text;
dad.InsertCommand.Parameters.Add("#City", SqlDbType.VarChar).Value = textBox2.Text;
dad.InsertCommand.Parameters.Add("#Brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.InsertCommand.Parameters.Add("#Lot_Num", SqlDbType.VarChar).Value = textBox5.Text;
dad.InsertCommand.Parameters.Add("#Area", SqlDbType.Int).Value = textBox6.Text;
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.InsertCommand.Parameters.Add("#Cenro", SqlDbType.VarChar).Value = textBox8.Text;
conn.Open();
dad.InsertCommand.ExecuteNonQuery();
conn.Close();
}
The problem here is the datetimepicker, in my sql server Mem_Date_Rec is a datetime, so whenever I try to run it and save something on my database,
dad.InsertCommand.ExecuteNonQuery();
Keeps on saying "Incorrect syntax near '#Cenro'."
Can anyone help me out here please, it would be a really great help.
I feel like you try to insert your parameter to dad.InsertCommand command not cmd command.
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
Because your dad.InsertCommand has a parameter called #Mem_Date_Rec, not cmd. I have no idea what is your cmd for exactly. It's useless this case. You can't add a parameter value in an SqlCommand that doesn't have any parameter definition.
Also use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection conn = new SqlConnection(ConnectionString))
using(SqlCommand cmd = conn.CreateCommand())
{
//
}
If you want to write a proper syntax code, you need start reading a book, articles, blogs, examples etc..
edit
You're missing something in your SQL. Change this:
> dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools
> (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec,
> Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area,
> #Mem_Date_Rec, #Cenro", conn);
To this
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro)", conn);
INSERT INTO table (columns) values (value)
you had: INSERT INTO table (columns) values (value
string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, Sur-Name, Score,Avg) VALUES ('" + fName + "','" + sName + "','" + lblScore.Text + "','" + lblAvg.Text + "');");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#Sur-Name", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
finally
{
connection.Close();
}
The error I keep getting is a runtime saying
Incorrect syntax near '-'. Incorrect syntax near '-'.
I used the try catch just so page would load and my scores show but the label says this Incorrect syntax as well, I was wondering could anyone please help me with what I am doing wrong
Thanks.
I think Sur-Name breaks your query. Use it with square brackets like [Sur-Name]
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. I see you tried to use but you never declare your parameter names in your query.
Also DATA might be a reserved keyword on future versions of SQL Server. You might need to use with also like [DATA]
Consider to use using statement to dispose your SqlConnection and SqlCommand.
using(SqlConnection connection = new SqlConnection(ConnectionString))
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = #"INSERT INTO [Data] (Name, [Sur-Name], Score, Avg)
VALUES (#Name, #SurName, #Score, #Avg)";
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
}
You are trying to mix concatenated queries with parametrized. Always use parametrized queries, It will save you from SQL Injection.
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Data] (Name, [Sur-Name], Score,Avg) VALUES (
#Name, #SurName, #Score, #Avg)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
Also consider enclosing your connection and command object in using statement.
As #Soner has mentioned in his answer, use Square brackets for Data and Sur-Name
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();
}
I get this error in ASP.NET Wizard when I try to use values of TextBox control of previous step.
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp".
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.
Is it a problem to access control's values of different steps?
This is the First class that inserts into dbo.Emp table
public void InsertInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String insertstring = #"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
values (#EmpID, #FirstName, #LastName, #MiddleName, #Mob1, #Mob2)";
SqlCommand cmd = new SqlCommand(insertstring, conn);
cmd.CommandText = insertstring;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.Parameters.AddWithValue("#FirstName", TextBox2.Text);
cmd.Parameters.AddWithValue("#LastName", TextBox3.Text);
cmd.Parameters.AddWithValue("#MiddleName", TextBox4.Text);
cmd.Parameters.AddWithValue("#Mob1", TextBox5.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox6.Text);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
And this is the one where I 'm inserting into the table where EmpID is a FK
public void Insertaddress()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String str = #"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
values(#Addressline1, #Addressline2, #CityID, #EmpID)";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandText = str;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#Addressline1", TextBox15.Text);
cmd.Parameters.AddWithValue("#Addressline2", TextBox17.Text);
cmd.Parameters.AddWithValue("#CityID", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
That was my problem.
A foreign key ensures that it cannot have a value in that column that is not also in the primary key column of the referenced table.
In your case , you are inserting EmpID into contact table which is not present in the referenced table of EmpID i.e Emp table.
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], ...)