Insert sql error ("where") - c#

I created some simple code, but it looks like something is working wrong with my Insert I get error about "where". What did I do wrong?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) where Login =#Login and Password=#Password and Type=#UserType ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}

SQL Insert Into statement is
INSERT INTO Table_Name ( Col1, Col2, Col3)
VALUES ( Val1, Val2, Val3);
I think,
insert into dbo.UserInfo (Login, Password, UserType, ID)
where Login =#Login and Password=#Password and Type=#UserType "
try to change the code to this.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) " +
" VALUES(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}

INSERT statements don't have WHERE clauses, UPDATE statements do.

You would only use a WHERE clause if there was an actual select statement.
Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
SELECT Login, Password, UserType, ID
FROM Table
where Login =#Login
and Password=#Password
and Type=#UserType
Otherwise you just use the values. Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
VALUES (#Login,#Password,#UserType, #ID)

Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Your query should probably be
"insert into dbo.UserInfo (Login, Password, UserType, ID) values (#Login, #Password, #UserType)"

I am not sure why you are using where while inserting single record to table. Below is the proper code to insert
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO UserInfo(Login, Password, UserType) VALUES(#Login,#Password,#Type)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#Login", TextBox1.Text);
cmd.Parameters.AddWithValue("#Password", TextBox2.Text + ".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}

Please, follow below syntex:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
=============
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType) values(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}

Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Only check your Insert Syntax you will get the answer :
"insert into dbo.xyz(Login, Password, ID) values (#Login, #Password)"
dbo:xyz = your table name

Related

C# Not able to insert records into my database

SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (ParticipantId, LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#ParticipantId, #LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
// cmd.Parameters.AddWithValue("#ParticipantId", notnull);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender.Text);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
cmd.ExecuteNonQuery();
cnn.Close();
I keep getting the error message:
"System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#ParticipantId".' "
I have tried this multiple ways and have been trying to figure this out for a week now. I'm not understanding what is the bug in my code.
Updated version below:
SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
//cmd.Parameters.AddWithValue("#ParticipantId", );
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
int nextKey;
cmd = new SqlCommand("SELECT MAX(ParticipantId) FROM Participant", cnn);
nextKey = (int)cmd.ExecuteScalar() + 1;
// cmd.ExecuteNonQuery();
cnn.Close();
if the column ParticipantId is marked as Identity Then You Should Not Try To Manually Insert data in it , sql server will populate it depending on last used ParticipantId , therefore u should remove the column from the insert statement and remove the id parameter .
if its just a Primary Key then u will need to manually insert unique value for each row .
the error mentioned above is because of the commented line which was supposed to provide a value for ParticipantId parameter

INSERT INTO Table (Column) VALUE (email)

I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)

Error in c# odbcCommand parameterization

Executing the below code gives me error. Column 'Username' cannot be null
Values are being passed in the variables. But I think the OdbcCommand statement is not prepared properly.
OdbcCommand cmd = new OdbcCommand
{
CommandText =
"INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(#username,#name,#email,#address,#contact_number,#html_email)",
Connection = Con
};
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#address", add);
cmd.Parameters.AddWithValue("#contact_number", contact);
cmd.Parameters.AddWithValue("#html_email", table);
billid = cmd.ExecuteScalar().ToString();
OdbcCommand does not support named parameter syntax, instead you should use a question mark placeholder:
OdbcCommand cmd = new OdbcCommand
{
CommandText =
"INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(?, ?, ?, ?, ?, ?)",
Connection = Con
};
cmd.Parameters.AddWithValue("#p1", username);
cmd.Parameters.AddWithValue("#p2", name);
cmd.Parameters.AddWithValue("#p3", email);
cmd.Parameters.AddWithValue("#p4", add);
cmd.Parameters.AddWithValue("#p5", contact);
cmd.Parameters.AddWithValue("#p6", table);
int affectedRecords = cmd.ExecuteNonQuery();
Try This:
OdbcCommand cmd = new OdbcCommand("INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(#username,#name,#email,#address,#contact_number,#html_email)",Con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#address", add);
cmd.Parameters.AddWithValue("#contact_number", contact);
cmd.Parameters.AddWithValue("#html_email", table);
billid = cmd.ExecuteNonQuery();
Use ExecuteNonQuery instead of ExecuteScalar() to execute the insert statement.
int affectedRows = cmd.ExecuteNonQuery();
You probably want to return the last inserted record Id, that's why you are using ExecuteScalar. OdbcCommand doesn't support then named parameters, so you need to use the placeholder in the query. So overall you need to change the query to this
CommandText = "INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(?,?,?,?,?,?) SELECT SCOPE_IDENTITY()";
Now you can use the ExecuteScalar()
billid = cmd.ExecuteScalar().ToString();

insert into two tables

I have 2 tables:
RESERVATION
ID, DATE, TIME, TABLE
CLIENT
ID_CLIENT, FNAME, LNAME, EMAIL, PHONE, FK_RESERVATION
I have working INSERT statement for Reservation Table-
string insertSql = "INSERT INTO Rezervacija (date,time,table) VALUES (#date,#time,#table);
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
But the problem comes with INSERT INTO Client Table Foreign Key.
Can anyone help me how to insert data into two related tables.
You'll need to modify your query to get the ID of the row that you just inserted.
string insertSql = "INSERT INTO Rezervacija (date,time,table) OUTPUT INSERTED.Id VALUES (#date,#time,#table);"
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
var **reservationId** = (int)cmd.ExecuteScalar()
string insertSql2 = "INSERT INTO CLIENT (ID_CLIENT,FNAME,LNAME,EMAIL,PHONE,FK_RESERVATION) VALUES (#clientId, #fname, #lname, #email, #phone, #reservation"
SqlCommand cmd2 = new SqlCommand(insertSql2, con);
cmd.Parameters.AddWithValue("#clientId", clientId);
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#reservation", **reservationId**);
This will allow you use the Inserted.Id in your second query as you've returned the output to a variable.

retrieve unique id for just added row

I am new to asp.net. I am executing a simple insert query via a SQL command. Now I want to retrieve the unique id for this newly inserted row and store it in an array. I do not know how to approach this problem.
My code
foreach (GridViewRow gvrow in gvuserdata.Rows)
{
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate", gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
//I want to store ID for this row after insert command
}
Use Select Scope_Identity() with Execute Scalar:
int returnID = 0;
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName,
CarName,Price,startdate,enddate)" + " values(#carid, #username,
#carname,#price,#startdate,#enddate); Select Scope_Identity()";
...
returnID = (int)cmd.ExecuteScalar();
I think your question is how retrieve the newly inserted record in the DB right? if that is the case your can fetch your by using the Scope_Identity()
int returnID = 0;
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate); Select Scope_Identity()";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
SqlDataReader reader = new SqlDataReader();
reader = cmd.ExecuteReader();
returnId = reader("Car_Id_Reference")
Hi Steve Insert one more column in your table with uniqueidentifier as datatype , and add Guid id to the column in codebehind which is uniquely identifiable
to creat GUID
// This code example demonstrates the Guid.NewGuid() method.
using System;
class CreateGUID
{
public static void Main()
{
Guid g;
// Create and display the value of two GUIDs.
g = Guid.NewGuid();
Console.WriteLine(g);
Console.WriteLine(Guid.NewGuid());
}
}
/*
This code example produces the following results:
0f8fad5b-d9cb-469f-a165-70867728950e
7c9e6679-7425-40de-944b-e07fc1f90ae7
*/
Above code is just for your reference to check the unique id generated each time now your code look like below
foreach (GridViewRow gvrow in gvuserdata.Rows)
{
Guid uniqueRowId = Guid.NewGuid();
string strQuery = "insert into vishalc.[Rental Table] (uniqueRowId, Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#uniqueRowId,#carid, #username, #carname,#price,#startdate,#enddate)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#uniqueRowId", uniqueRowId);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate",gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
cmd.CommandType = CommandType.Text;``
cmd.Connection = con;
cmd.ExecuteNonQuery();
//I want to store ID for this row after insert command
}
NOTE: Make sure that you have update the column in the TABLE
Please try adding output parameter and SCOPE_IDENTITY output parameter:
int RetVal = 0;
foreach (GridViewRow gvrow in gvuserdata.Rows)
{
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate);set #out=SCOPE_IDENTITY()";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate", gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
SqlParameter outpar = new SqlParameter("#out", SqlDbType.Int);
outpar.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outpar);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
if (outpar != null)
RetVal = Convert.ToInt32(outpar.Value);
}
Must set the primarykey and Identity="yes" in your column.
Then you can use scopIdentity
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate); **Select Scope_Identity();**";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate", gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
**Guid Id=(Guid)(cmd.ExecuteNonQuery());**
See this below line
Guid Id=(Guid)(cmd.ExecuteNonQuery())
You want to guid .So I am converted to guid .

Categories

Resources