I have this code for inserting data into database using Windows forms application.
But I get this error
Could not find stored procedure 'sp_insert'
I am not using any external server and it's a Local db
UPDATE: it seemed that I don't have a stored procedure so I tried to create one but it throws another error
CREATE PROCEDURE sp_insert
#UserName varchar(20),
#Password varchar(18),
#Email varchar(50),
#Name varchar(20),
#Surname varchar(20)
AS
-- here the error occurs "error near syntax" but User is my table name
-- and it's correct I don't know what is the problem is
INSERT INTO User (UserName, Password, Email, Name, Surname)
VALUES (#UserName, #Password, #Email, #Name, #Surname)
C# code:
SqlConnection con = new SqlConnection(#"Data Source= (LocalDB)\v11.0;AttachDbFilename=D:\TaxiBooking\TaxiBooking\TaxiBooking\Registraion.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand("sp_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserName",txtUser.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Surname", txtSurname.Text);
con.Open();
cmd.ExecuteNonQuery();
why don't you try dbo.sp_insert.
SqlCommand cmd = new SqlCommand("dbo.sp_insert", con);
You are using a reserved word:
Change
INSERT INTO User( UserName,Password,Email,Name,Surname)
to
INSERT INTO [User]( UserName,Password,Email,Name,Surname)
Try to avoid the use of terms that look like they will be shared with the OS or application you are coding against. You will save yourself some headaches.
Related
I'm writing a lab for a C# class to manage an Access database. It's a C# GUI program that uses a DataGridView to view a database and write to it.
The save table class will not work and gives me the same exception: SystemData.OleDb.OleDbException: 'Data type mismatch in criteria expression.'
I understand the code might be vulnerable to SQL injection but this is a one time lab that's on the clock, need to get a solution to the problem at hand. Not worried about parameters unless they'd fix this issue.
private void button2_Click_1(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/sdepasqu/Documents/Customer Database.accdb";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (OleDbConnection conn = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(#"INSERT INTO customer([CUST_ID], [FIRST_NAME], [LAST_NAME], [ADDRESS], [CITY], [STATE], [POSTAL], [EMAIL], [BALANCE], [CREDIT_LIMIT], [REP_ID]) VALUES(#cust_id, #first_name, #last_name, #address, #city, #state, #postal, #email, #balance, #credit_limit, #rep_id)", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#id", row.Cells["iDDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#cust_id", row.Cells["cUSTIDDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#first_name", row.Cells["fIRSTNAMEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#last_name", row.Cells["lASTNAMEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#address", row.Cells["aDDRESSDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#city", row.Cells["cITYDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#state", row.Cells["sTATEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#postal", row.Cells["pOSTALDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("email", row.Cells["eMAILDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#balance", row.Cells["bALANCEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#credit_limit", row.Cells["cREDITLIMITDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#rep_id", row.Cells["rEPIDDataGridViewTextBoxColumn"].Value);
cmd.ExecuteNonQuery();
}
}
}
}
The database table in question:
Tried to do a cmd.Parameters.Add and specify the OleDbDataType but it threw up a bunch of errors at me.
Here is an example of cmd parameter:
cmd.Parameters.Add("#item_number", SqlDbType.VarChar).Value = lblitemnum.Text;
Go through your table and write down what type each column is , and re-write your code compared to example above. AutoNumber will probably be int, shorttext should be varchar, cust_id should be int also. Currency should be money, an so on.
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.
I am passing the parameter like in C# page,
conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.CommandText = commandtype.storedprocedure;
cmd.Parameters.AddWithValue("?user", user)
cmd.Parameters.AddWithValue("?name", name);
On the mysql stored procedures used 2 parameter for record exists finds
#id integer,
#name varchar(200)
BEGIN
IF EXISTS (SELECT * FROM usertable WHERE id = #id and mode =0 limit 1 )
THEN
UPDATE usertable SET name = name where id=#id and mode = 0;
ELSE
INSERT INTO usertable (name, mode)VALUES (#name`enter code here`,0);
END IF;
END
Another way of sending variables to a stored proc that I've used with no problem:
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#name", SqlDbTpye.Varchar).Value = name;
I think you can specify variable by size and type like this:
SqlDbTpye.Varchar,200
But not able to test that right now.
You need to make sure the prefixes for the parameters match. If you use "#" in your stored procedure, you need to use "#" in C#, too, not "?".
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#user", user)
cmd.Parameters.AddWithValue("#name", name);
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.
I am getting an SQLException "Operand type clash: int is incompatible with uniqueidentifier"
when I am trying to execute the below stored procedure from C# code.
create proc sp_Get_Allfields_Account_Public
#username varchar(20),
#password varchar(20),
#acc_num UniqueIdentifier out,
#cust_name varchar(20) out,
#balance float out
as
select #acc_num=acc_num,#cust_name=cust_name,#balance=balance from Account_Public where username=#username and password=#password
C# code is as follows
cmd = new SqlCommand("sp_Get_Allfields_Account_Public", con);
cmd.CommandType = CommandType.StoredProcedure;
// Add Input Parameters
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
// Add output parameters
cmd.Parameters.AddWithValue("#acc_num", SqlDbType.UniqueIdentifier);
cmd.Parameters["#acc_num"].Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#cust_name", SqlDbType.VarChar);
cmd.Parameters["#cust_name"].Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#balance", SqlDbType.Float);
cmd.Parameters["#balance"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
Table definition
create table Account_Public
(
acc_num uniqueidentifier,
cust_name varchar(20),
username varchar(20),
password varchar(20),
balance float
)
It's because you're calling AddWithValue, then passing the value as the enum (which is interpreted as an int).
cmd.Parameters.AddWithValue("#acc_num", SqlDbType.UniqueIdentifier);
Use a different method (probably just Add).
This may seem a bit redundant, but are you sure that the data type of column [Account_Public].[acc_num] is actually uniqueidentifier and not int?
Try this instead:
cmd = new SqlCommand("select #acc_num=acc_num,#cust_name=cust_name,#balance=balance from Account_Public where username=#username and password=#password", con);
cmd.CommandType = CommandType.Text;
with the same parameters. Do you get the same error?
Also, I strongly recommend that you specify explicit sizes on all the char parameters. It's not so important for the input parameters, but it's very important for the output ones.