Try/Catch method error ASP.NET - c#

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.

Related

Attempting to INSERT values into a MySQL DB from C# code within a form, but getting "Column cannot be NULL

All - thanks in advance for your time. So, background info - I am trying to create a form for contact registration using C# to pass the information into my MySql DB. If I use the query directly in the code, it works. However, I have read that you should use a stored procedure for security. So, working code is:
using (MySqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"INSERT INTO Contacts (contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell) VALUES (#ciD,#ln, #fn, #add, #city, #state, #zip, #email, #news, #cell)";
//cmd.CommandText = "insert_contact";
//cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#cID", MySqlDbType.VarChar);
cmd.Parameters.Add("#ln", MySqlDbType.VarChar);
cmd.Parameters.Add("#fn", MySqlDbType.VarChar);
cmd.Parameters.Add("#add", MySqlDbType.VarChar);
cmd.Parameters.Add("#city", MySqlDbType.VarChar);
cmd.Parameters.Add("#state", MySqlDbType.VarChar);
cmd.Parameters.Add("#zip", MySqlDbType.VarChar);
cmd.Parameters.Add("#email", MySqlDbType.VarChar);
cmd.Parameters.Add("#news", MySqlDbType.Bit);
cmd.Parameters.Add("#cell", MySqlDbType.Bit);
cmd.Parameters["#cID"].Value = default;
cmd.Parameters["#ln"].Value = lastName_TextBox.Text;
cmd.Parameters["#fn"].Value = firstName_TextBox.Text;
cmd.Parameters["#add"].Value = address_TextBox.Text;
cmd.Parameters["#city"].Value = city_TextBox.Text;
cmd.Parameters["#state"].Value = state_DropDown.Text;
cmd.Parameters["#zip"].Value = zipCode_TextBox.Text;
cmd.Parameters["#email"].Value = email_TextBox.Text;
cmd.Parameters["#news"].Value = newsletter_CheckBox.Checked;
cmd.Parameters["#cell"].Value = cell_CheckBox.Checked;
cmd.ExecuteNonQuery();
conn.Close();
However, when I change the following lines to this, I get the "cannot be NULL error":
conn.Open();
//cmd.CommandText = #"INSERT INTO Contacts (contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell) VALUES (#ciD,#ln, #fn, #add, #city, #state, #zip, #email, #news, #cell)";
cmd.CommandText = "insert_contact";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
My stored procedure on the DB is (I suspect this is where the error may be):
BEGIN
INSERT INTO Contacts (contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell)
VALUES (#ciD,#ln, #fn, #add, #city, #state, #zip, #email, #news, #cell);
END
I have attempted the following, with the accompanying errors:
• Changed the "#" in the stored procedures to a "?" -(Get an error in SQL Syntax)
• Changing all of the columns to accept a NULL value. -(All columns then have a NULL value).
My apologies if this is something easy - just starting out learning.
Thanks in advance!
Pherix
Your insert_contact stored procedure have to provide the parameters (with the type) as below:
CREATE PROCEDURE insert_contact
(
IN cID VARCHAR,
IN ln VARCHAR(30),
IN fn VARCHAR(45),
IN `add` VARCHAR(30),
IN city VARCHAR(30),
IN state VARCHAR(10),
IN zip VARCHAR(20),
IN email VARCHAR(45),
IN news bit,
IN cell bit,
)
BEGIN
INSERT INTO Contacts
(contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell)
VALUES
(#cID, #ln, #fn, #add, #city, #state, #zip, #email, #news, #cell);
END
And in case there is any parameter which conflict with MySQL reserved words, you need to escape the reserved words with single quotes.
Note:
Your contactID column was int(11) type but you provide the cID parameter as VARCHAR type. You need to take concern that the column type was unmatched and possible lead an exception.
Reference
MySQL - Working with Stored Procedures
Ok, finally found what the Stored Procedure liked:
BEGIN
INSERT INTO Contacts
(last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell)
VALUES
(ln, fn, address, city, state, zip, email, news, cell);
END
Apparently, it did not like the "#" in front of the passed values.

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);

Issue with Inserting integer and string into SQL Server database c#

I am having trouble inserting the integer value [Question Type] and the string [Question Space] into my database at the same time into the same row. Whenever I click the button and try to execute an error comes up saying:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near '('.
Code:
SqlCommand command5 = new SqlCommand("INSERT INTO ([Question Space], [Question Type]) Questions VALUES ('#QuestionText', '#checkedradiobutton')", connect);
command5.Parameters.AddWithValue("#QuestionText", QuestionText);
command5.Parameters.AddWithValue("#checkedradiobutton", checkedradiobutton);
command5.ExecuteNonQuery();
I would appreciate any help that anyone can give me.
Here's the whole code for the button if you want to see:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
int checkedradiobutton = 0;
if(radioButton1.Checked)
{
checkedradiobutton = 1;
}
else if(radioButton2.Checked)
{
checkedradiobutton = 2;
}
else if(radioButton3.Checked)
{
checkedradiobutton = 3;
}
string QuestionText = QuestionBox.Text;
SqlCommand command5 = new SqlCommand("INSERT INTO ([Question Space], [Question Type]) Questions VALUES ('#QuestionText', '#checkedradiobutton')", connect);
command5.Parameters.AddWithValue("#QuestionText", QuestionText);
command5.Parameters.AddWithValue("#checkedradiobutton", checkedradiobutton);
command5.ExecuteNonQuery();
}
And my database table:
CREATE TABLE [dbo].[Questions]
(
[QuestionID] INT IDENTITY (1, 1) NOT NULL,
[Actual answer] NVARCHAR (50) NULL,
[Question Space] NVARCHAR (50) NULL,
[Question Type] INT NULL,
PRIMARY KEY CLUSTERED ([QuestionID] ASC)
);
The correct syntax for INSERT INTO is
INSERT INTO <table> (field1, field2, fieldN) VALUES (value1, value2, valueN)
so your command should be written as
SqlCommand command5 = new SqlCommand(#"INSERT INTO Questions
([Question Space], [Question Type]) VALUES
(#QuestionText, #checkedradiobutton)", connect);
Note how the parameters placeholders should not be enclosed in single quotes because doing that you tranform them in literal text. (Inserts the "#QuestionText" string in your [Question Space] field)
Finally, try to avoid AddWithValue, it is a shortcut with numerous drawbacks as you can read in Can we stop using AddWithValue already and in How Data Access Code Affects Database Performance
This is still a single line of code
command5.Parameters.Add("#QuestionText", SqlDbType.NVarChar).Value = QuestionText;
You don't have to wrap parameters with ' inside the query. Start cleaning it and see if it works
SqlCommand command5 = new SqlCommand("INSERT INTO [dbo].[Questions] ([Question Space], [Question Type]) Questions VALUES (#QuestionText, #checkedradiobutton)", connect);
command5.Parameters.AddWithValue("#QuestionText", QuestionText);
command5.Parameters.AddWithValue("#checkedradiobutton", checkedradiobutton);
command5.ExecuteNonQuery();
The INSERT syntax is wrong, the name of the table should go after "INSERT INTO", e.g.:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Cheers.

Inserting with an Auto-Incrementing ID

I am inserting into a database using a stored procedure and i am getting the error:
Procedure or function 'sp_Addrecord' expects parameter '#RecordNumber', which was not supplied.
RecordNumber is an auto incrementing ID so i understand id have to omit it from my insert command and specify which columns and where i have to insert to avoid this but i am calling the procedure which is handled by another class so where would i be able to specify this as you would normally say something like this:
SqlCommand cmd = new SqlCommand("INSERT INTO CARS (carDate, carTime) Values (#Date, #Time)", conDatabase);
Here is my code, i avoided the using statement for simplicity of this example:
List<CarRecord> carRecords;
private void Save_Record_Click(object sender, RoutedEventArgs e)
{
SqlConnection conDatabase = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
conDatabase.Open();
SqlCommand cmd = new SqlCommand("sp_Addrecord", conDatabase);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conDatabase.Close();
}
public bool Addrecord(CarRecord DataRecord)
{
return ExecuteNonQuery("sp_Addrecord", null,
CreateParameter("#Date", SqlDbType.NVarChar, DataRecord.carDate),
CreateParameter("#Time", SqlDbType.NVarChar, DataRecord.carTime),
);
}
EDIT - Stored Procedure:
USE [SDC Logging]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_Addrecord]
#RecordNumber int,
#Date nvarchar(50),
#Time nvarchar(50),
AS
BEGIN
SET NOCOUNT ON;
WITH [source](RecordNumber, Date, Time)
AS
(
SELECT #RecordNumber, #Date, #Time,
)
MERGE dbo.Bags AS [target] USING [source]
ON [target].Date = [source].Date
WHEN MATCHED THEN UPDATE SET
[target].Date = #Date,
[target].Time = #Time,
WHEN NOT MATCHED THEN
INSERT ( Date, Time, )
VALUES( #Date, #Time, );
SELECT SCOPE_IDENTITY()
END
The error says it all. Your sp_Addrecord has a parameter specified that you are supplying. Basically, the parameters you specify here...
return ExecuteNonQuery("sp_Addrecord", null,
CreateParameter("#Date", SqlDbType.NVarChar, DataRecord.carDate),
CreateParameter("#Time", SqlDbType.NVarChar, DataRecord.carTime),
);
must match the name and datatype of the parameters defined by sp_Addrecord stored procedure. In addition, make sure your stored procedure's query matches this query...
INSERT INTO CARS (carDate, carTime) Values (#Date, #Time)
Edit based on your Edit
You need to specified the #RecordNumber parameter here...
return ExecuteNonQuery("sp_Addrecord", null,
CreateParameter("#RecordNumber", SqlDbType.Int, DataRecord.recordNumber),
CreateParameter("#Date", SqlDbType.NVarChar, DataRecord.carDate),
CreateParameter("#Time", SqlDbType.NVarChar, DataRecord.carTime),
);
Don't worry about the insert just make sure that when inserting you pass a "invalid record number" such as -1, if the MERGE statement doesn't find the record with id of -1 it will successfully insert the record with an auto-generated Id with the help of your identity column
Try This.
You don't need to call separate method Addrecord.
However, you still want to use a separate method. Add code below in the AddRecord method and remove existing code:
SqlParameter []parms = new SqlParameter[1];
parms[0] = new SqlParameter("#Date",DataRecord.carDate) ;
parms[1] = new SqlParameter("#Time",DataRecord.carTime) ;
cmd.Parameters.AddRange(parms);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conDatabase.Close();

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.

Categories

Resources