I have a table which i want to store all the outputs into one row seperated by a space(eg "textbox1 textbox2 textbox3". How would i do this? At the moment its trying to put them into different columns. Giving me an error stating im using fewer columns.
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#textbox1, #textbox2, #textbox3)", cn))
{
cmd.Parameters.AddWithValue("#textbox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textbox2", textBox2.Text);
cmd.Parameters.AddWithValue("#textbox3", textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
}
Try this:
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#text)", cn))
{
cmd.Parameters.AddWithValue("#text", textBox1.Text + " " + textBox2.Text + " " + textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
You are inserting data in more column than you have specified so I think you have got the error in that part. So, make some modification in code to remove the error:
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#textbox1+' '+ #textbox2+' '+ #textbox3)", cn))
{
cmd.Parameters.AddWithValue("#textbox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textbox2", textBox2.Text);
cmd.Parameters.AddWithValue("#textbox3", textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
}
Related
I tried to find it. But I can't found exactly my answer. So I decide to ask this questions. I need your help.
I want add value into table value without overwriting Debit, Score column. It will add current value.
cmd = new SqlCommand("UPDATE Users SET Debit=#debit,
Score=#score
WHERE Phone=#phone", con);
con.Open();
cmd.Parameters.AddWithValue("#phone", textBox1.Text);
cmd.Parameters.AddWithValue("#debit", textBox2.Text);
cmd.Parameters.AddWithValue("#score", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Амжилттай");
con.Close();
For example:
Table, Phone: 999 | Debit: 1500 | Score: 100 //current <br>
When I add value from textBox1 = 999, textBox2 = 500, textBox3 = 50
Table, Phone: 999, Debit: 2000, Score: 150 //updating like that
I know SQL query like that. But I don't know how to write code in SqlCommand
UPDATE Users
SET Debit = Debit + [user input], Score = Score + [user input]
WHERE = Phone
Any suggestions?
(Sorry for my horrible English I hope you guys understand What I'm trying to ask)
Thanks
If you want to add, just add:
cmd = new SqlCommand(#"UPDATE Users
SET Debit = Debit + #debit,
Score = Score + #score
WHERE Phone = #phone", con);
Please, notice verbatim string #"..." syntax. Please, do not forget about disposing (explicit Close is an antipattern):
string sql =
#"UPDATE Users
SET Debit = Debit + #debit,
Score = Score + #score
WHERE Phone = #phone";
//TODO: put the right connection string instead of "MyConnectionStringHere"
//DONE: IDisposable (SqlConnection) should be wrapped into using
using (var con = new SqlConnection("MyConnectionStringHere")) {
con.Open();
//DONE: IDisposable (SqlCommand) should be wrapped into using
using (var cmd = new SqlCommand(sql, con)) {
//TODO: AddWithValue is often a bad choice; change to Add
cmd.Parameters.AddWithValue("#phone", textBox1.Text);
cmd.Parameters.AddWithValue("#debit", textBox2.Text);
cmd.Parameters.AddWithValue("#score", textBox3.Text);
cmd.ExecuteNonQuery();
//TODO: a better policy is to read localized strings from resources
MessageBox.Show("Амжилттай");
}
}
This will help you....just try in this way..
SqlCommand cmd = new SqlCommand("UPDATE Users SET Debit = Debit + " + textBox2.Text + ", Score = Score + " + textBox3.Text + " WHERE Phone = " + textBox1.Text + "", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Амжилттай");
con.Close();
OR
SqlCommand cmd = new SqlCommand("UPDATE Users SET Debit = Debit + #debit, Score = Score + #score WHERE Phone = #phone", con);
con.Open();
cmd.Parameters.AddWithValue("#phone", textBox1.Text);
cmd.Parameters.AddWithValue("#debit", textBox2.Text);
cmd.Parameters.AddWithValue("#score", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Амжилттай");
con.Close();
You can use += operator for update. Change your sql command like this;
UPDATE Users SET Debit+=#debit,
Score+=#score
WHERE Phone=#phone
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.
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
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], ...)
I want to check if record exists or not if it exists i dont want to insert if it bot i want to insert the data in ms access database in c#.
OleDbCommand cmd = new OleDbCommand("insert into MyTable values('" + test + "','" + test + "','" + "123" + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);
temp = 0;
try
{
con.Open();
string count = (string)cmd1.ExecuteScalar();
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("One Record Added");
}
else
{
MessageBox.Show("Record not added");
}
}
catch
{ }
Can Anyone suggest me some code.
Thanks In Advance.
Filter your Select query on the basis of some key . Check if it returns for existence or non-existence of the particular record and do the processing required .
string cmdStr = "Select count(*) from MyTable where id = 1"; //get the existence of the record as count
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
int count = (int)cmd.ExecuteScalar();
if(count >0)
{
//record already exist
}
Modify this line
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);