Error with SqlCommand and connection in C# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have errors with this code, but cannot find the problem. Please help.
SqlConnection myConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Software Project\BakeryProject Pages\BakeryProject\Databases\Users.mdf; Integrated Security = True");
myConnection.Open();
string commandText = "INSERT INTO Table (Id, Username, First_name, Last_Name, Password, Client, Staff, Admin )";
commandText += "VALUES (1, 'JohnSmith', 'John', 'Smith', 'Pass1', 'Client');";
SqlCommand myCommand = new SqlCommand(commandText, myConnection);
myCommand.Parameters.AddWithValue("#Id", mID);
myCommand.Parameters.AddWithValue("#Username", mUsername);
myCommand.Parameters.AddWithValue("#First_name", mNameFirst);
myCommand.Parameters.AddWithValue("#Last_name", mNameLast);
myCommand.Parameters.AddWithValue("#Password", mPassword);
myCommand.Parameters.AddWithValue("#Client", mClient);
myCommand.ExecuteNonQuery();

You are trying to add params, but you never defined any in your query. Perhaps this is what you meant:
string commandText = "INSERT INTO [Table] (Id, Username, First_name, Last_Name, Password, Client) ";
commandText += "VALUES (#Id, #Username, #First_name, #Last_name, #Password, #Client);";
SqlCommand myCommand = new SqlCommand(commandText, myConnection);
myCommand.Parameters.AddWithValue("#Id", mID);
myCommand.Parameters.AddWithValue("#Username", mUsername);
myCommand.Parameters.AddWithValue("#First_name", mNameFirst);
myCommand.Parameters.AddWithValue("#Last_name", mNameLast);
myCommand.Parameters.AddWithValue("#Password", mPassword);
myCommand.Parameters.AddWithValue("#Client", mClient);
myCommand.ExecuteNonQuery();
Note: I've also removed the Staff and Admin columns from your script as they don't have a param mentioned below. This should give you a point in the right direction though.
As a side-note, it's much easier to declare queries in C# by using a string literal. This way, you don't have to mess with the += and weird spacing issues that come from it:
string commandText =
#"
Insert [Table] (Id, Username, First_name, Last_Name, Password, Client)
Values (#Id, #Username, #First_name, #Last_name, #Password, #Client);
";

Related

Syntax Error with INSERT statement. C# Access Database

Trying to add a new record to a database. I have tried this type of code on a different project and it worked fine.
I keep getting a Syntax Error on INSERT statement:
I cannot seem to find the problem. I have searched for ages at other solutions that did not work. I have checked the table names a few times now and I can't see any inconsistencies.
Please note that I do have all the other remaining code to add the record, but didn't include it here.
Any help would be great. If anyone needs anymore information I will gladly comply.
I am working with C# and using Access Database.
void addRecord()
{
OleDbConnection myDatabaseConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=..\..\Database\TestionRetail.accdb;");
System.Data.OleDb.OleDbCommand command = new OleDbCommand();
command.Connection = myDatabaseConnection;
myDatabaseConnection.Open();
command.CommandText = "INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)" +
"VALUES (#PayrollNo, #Title, #FirstName, #Surname, #Position, #DOB, #Email, #PhoneNumber, #AlternateNumber, #AddressLine1, #AddressLine2, #City, #Postcode, #ContractType)";
command.Parameters.AddWithValue("#PayrollNo", txtPayroll.Text);
command.Parameters.AddWithValue("#Title", cmbTitle.SelectedIndex.ToString());
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Position", txtPosition.Text);
command.Parameters.AddWithValue("#DOB", dtpDOB.Value.ToShortDateString());
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#PhoneNumber", txtPhoneNo.Text);
command.Parameters.AddWithValue("#AlternateNumber", txtAltPhoneNo.Text);
command.Parameters.AddWithValue("#AddressLine1", txtAddress1.Text);
command.Parameters.AddWithValue("#AddressLine2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtTown.Text);
command.Parameters.AddWithValue("#Postcode", mtbPostcode.Text);
command.Parameters.AddWithValue("#ContractType", cmbContract.SelectedIndex.ToString());
try
{
command.ExecuteNonQuery();
var item = new NotifyIcon(this.components);
item.Visible = true;
item.Icon = System.Drawing.SystemIcons.Information;
item.ShowBalloonTip(2000, "Record Added", "Successfully added new record", ToolTipIcon.Info);
this.Hide();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
//5. Close the database
myDatabaseConnection.Close();
this.Hide();
}
Thanks for the help everyone, I fixed the problem by putting square brackets in
I believe you need a space after the closing parenthesis on the following line:
command.CommandText = "INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)" +
Otherwise your query will read:
INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)VALUES (#PayrollNo, #Title, #FirstName, #Surname, #Position, #DOB, #Email, #PhoneNumber, #AlternateNumber, #AddressLine1, #AddressLine2, #City, #Postcode, #ContractType)
Which is why it is saying after INSERT because that's the first/last keyword it recognises before it encounters a syntax error.
A date field is not text. Thus:
command.Parameters.AddWithValue("#DOB", dtpDOB.Value);

Trying to add a string value to a SQL database - help and advice [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to add a string value to a SQL database in SQL Server Managemnet Studio but this does not work.
What is the correct way to do this?
SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES(" + txtProductName.Text + ");", sqlConnect);
try
{
addProduct.ExecuteNonQuery();
MessageBox.Show("This product has been succesfully added to the database!!");
}
catch (Exception error2)
{
MessageBox.Show(error2.ToString());
}
It seems that you forgot to include a quote for the added string. Something like this
SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES('" + txtProductName.Text + "');", sqlConnect);
Let's consider what is being generated here:
addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES(" + txtProductName.Text + ");", sqlConnect);
If the value of txtProductName.Text is "monkey nuts", then your SqlCommand will have a CommandText of:
INSERT INTO dbo.Test VALUES(monkey nuts);
This isn't valid SQL, as the string has not been quoted. Now, if the value of txtProductName.Text is "'foo');DROP TABLE Test; --", then your SqlCommand will have a CommandText of:
INSERT INTO dbo.Test VALUES('foo');DROP TABLE Test; --);
Which, whilst valid SQL (as I'd put the apostrophes in the text box to quote the string), isn't what you'd want to do either.
The safest approach is to use parametrisation, so something more like:
using (SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES(#ProductName);", sqlConnect);
{
addProduct.Parameters.Add("#ProductName", SqlDbType.NVarChar, 50).Value = txtProductName.Text;
addProduct.ExecuteNonQuery();
MessageBox.Show("This product has been succesfully added to the database!!");
}

Insert statement into SQL Server db

I'm developing an ASP.NET MVC Web Application using SQL Server.
I am trying to INSERT a new entry into my database and I don't understand what am I doing wrong.
I get an exception on the line:
command.ExecuteNonQuery();
The code is:
try
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=UniversityManager;Integrated Security=True");
using (connection)
{
//SqlCommand command = new SqlCommand(
// "INSERT INTO Students VALUES(#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp);",
// connection);
connection.Open();
String sql = "INSERT INTO Students(Id,Name,Surname,Year,PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#Id", SqlDbType.Int);
command.Parameters["#Id"].Value = 5;
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = collection.Name;
command.Parameters.Add("#Surname", SqlDbType.VarChar);
command.Parameters["#Surname"].Value = collection.Surname;
command.Parameters.Add("#Year", SqlDbType.Int);
command.Parameters["#Year"].Value = collection.Year;
command.Parameters.Add("#PhoneNumber", SqlDbType.VarChar);
command.Parameters["#PhoneNumber"].Value = collection.PhoneNumber;
command.Parameters.Add("#Cnp", SqlDbType.VarChar);
command.Parameters["#Cnp"].Value = collection.Cnp;
command.ExecuteNonQuery();
connection.Close();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Thank you!
YEAR is a reserved keyword for Sql Server. So, if you really have a column with that name, then you need to enclose it in square brackets every time you refer to it. Better change that name
String sql = "INSERT INTO Students(Id,Name,Surname,[Year],PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
Another possibility is the Id column. If this column has the IDENTITY property set to true, then you should not set a value for it. It is automatically calculated by the database engine.
Looking at your innerexception message, it seems the problem is due to one or more of your parameters contains more text than allowed by the database field size.
You could try something like this (for each varchar parameter)
// Assuming the Name field is defined as varchar(15)
command.Parameters.Add("#Name", SqlDbType.VarChar, 15);
command.Parameters["#Name"].Value = collection.Name;
The String or binary data would be truncated exception means you're trying to insert a value that is too large for one of the columns in your Student table. For example, your Name field has a maximum length of 10 but you're trying to insert a 15 character name.
Check the values you're inserting and see if they're too large for the columns.

Erorr on my Insert statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm having trouble with my code, I am getting a Invalid expression term ')' not sure what I'm doing wrong. Here is my code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source = '" + Server.MapPath("WSC_DB.mdb") + "'; Persist Security Info=False");
using (OleDbCommand cmd = new OleDbCommand("insert into Users(UserFirstName, UserLastName, ShipAddress, ShipCity, ShipState, UserPhone, UserEmail, UserName, UserPassword, LoginType) values (#FirstName, #LastName, #Address, #City, #State, #Zip, #Phone, #Email, #Username, #Password, #Logintype)", conn))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Parameters.AddWithValue("#State", DropDownList1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Zip", txtZip.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#Logintype", "U");
conn.Open();
cmd.ExecuteNonQuery();
}
}
You have 10 items in your columns list and 11 items in your values list. The values list includes
... #City, #State, #Zip, #Phone, #Email, ...
but there is no Zip in the columns list
... ShipCity, ShipState, UserPhone, UserEmail, ...
I seem to remember to that you cannot use named parameters in SQL statement when using Jet OLEDB. You will need to replace #FirstName, #LastName, ... with a question mark '?'.
For better analysis of your error please include the entire error message and stack trace.

Try/Catch method error ASP.NET

I'm trying to make this work. I want it to check if a record exist after inserting but it always return an error: Line 1: Incorrect syntax near 'nvarchar'. Can someone point out to me whats wrong in my declaration? Also if you have a better try catch method please enlighten me more. Just new to programming in ASP.NET
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
string connString_LibrarySystem = "Server=DEVSERVER;User ID=sa;Password=Sup3r-Us3r;Database=LibrarySystem";
string strSQL = "INSERT INTO TblBooks (bookid, booktitle, lastname, firstname, description, categoryid, dateadded, statusid, quantity, isdeleted) VALUES (#bookid, #booktitle, #lastname, #firstname, #description, #categoryid, #dateadded, #statusid, #quantity, #isdeleted)";
SqlConnection conn = new SqlConnection(connString_LibrarySystem);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand(strSQL, conn);
cmd.Parameters.AddWithValue("#bookid", Request.Form["bookid"]);
cmd.Parameters.AddWithValue("#booktitle", Request.Form["booktitle"]);
cmd.Parameters.AddWithValue("#lastname", Request.Form["lastname"]);
cmd.Parameters.AddWithValue("#firstname", Request.Form["firstname"]);
cmd.Parameters.AddWithValue("#description", Request.Form["description"]);
cmd.Parameters.AddWithValue("#categoryid", Request.Form["categoryid"]);
cmd.Parameters.AddWithValue("#dateadded", Request.Form["dateadded"]);
cmd.Parameters.AddWithValue("#statusid", Request.Form["statusid"]);
cmd.Parameters.AddWithValue("#quantity", Request.Form["quantity"]);
cmd.Parameters.AddWithValue("#isdeleted", Request.Form["isdeleted"]);
cmd.ExecuteNonQuery();
{
conn.Close();
}
statuslabel.Text = "Insert successful";
}
EDIT: There just removed the datatypes.
You don't have to include data type in insert statements. Skip them.
Try
string strSQL = "INSERT INTO TblBooks (bookid, booktitle, lastname, firstname, description, categoryid, dateadded, statusid, quantity, isdeleted) VALUES (#bookid, #booktitle , #lastname, #firstname, #description, #categoryid, #dateadded , #statusid , #quantity, #isdeleted)";
don't put the types in your values.
string strSQL = "INSERT INTO TblBooks (bookid, booktitle, lastname, firstname, description, categoryid, dateadded, statusid, quantity, isdeleted) VALUES (#bookid , #booktitle , #lastname , #firstname , #description , #categoryid , #dateadded , #statusid , #quantity , #isdeleted )";
In order to make this work you need to remove the datatypes from the sqlstring variable.
I would probably switch to using a stored procedure and then load parameters since that's basically what you're doing here with the addwithvalue command
also cmd.ExecuteNonQuery() will return an int to tell you that it's been added successfully. if it returns a 1 you know that's it's complete.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
At first, remove your types in the SQL, you do not need them (As other answers suggested)
Second, you add a parameter to the query by this :
cmd.Parameters.AddWithValue("#bookid", Request.Form["bookid"]);
You do not make sure that Request.Form["bookid"] is not null, this will cause your current problem
Get rid of the data types in the values list. You don't need them.

Categories

Resources