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'm trying to insert data from my ASP.NET web application into a SQL Server database table (which I have previously created). The code I have doesn't seem to be working, the error message displays, and the actual data doesn't appear to get saved to the database.
var conn = new SqlConnection("Data Source=SHRIYA\\SQLEXPRESS;Initial Catalog=…;Integrated Security=True");
var insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password", conn);
insert.Parameters.AddWithValue("#GenerteID",lstuserID.SelectedIndex);
insert.Parameters.AddWithValue("#Name", txtname.Text);
insert.Parameters.AddWithValue("#Surname", txtsurname.Text);
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
insert.Parameters.AddWithValue("#Gender", ddlgender.SelectedItem);
insert.Parameters.AddWithValue("#Address", txtaddress.Text);
insert.Parameters.AddWithValue("#Postal_code", txtpostalcode.Text);
insert.Parameters.AddWithValue("#Phone_Number", txttele.Text);
insert.Parameters.AddWithValue("#Email", txtEmail.Text);
insert.Parameters.AddWithValue("#Password", txtpassword);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch (Exception)
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Error When Saving');", true);
}
conn.Close();
One error is to use txtpassword (i.e. a UI control as a whole) as a value for a SqlParameter. Replace it with txtpassword.Text (i.e. the textual value entered into the UI control):
insert.Parameters.AddWithValue("#Password", txtpassword.Text);
Your SQL command text is missing the closing parenthesis ) for VALUES (:
SqlCommand insert = new SqlCommand("Insert Into
tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,
Postal_code,Phone_Number,Email,Password)
values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,
#Postal_code,#Phone_Number,#Email,#Password)", conn);
// ^
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
That should be
insert.Parameters.AddWithValue("#ID_Number", txtid.Text);
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password", conn);
SQL syntax is wrong.
Missing ) at the last parameter #Password.
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password)", conn);
Related
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 6 years ago.
Improve this question
Here is my code for adding data to my database.
try
{
String id = txtId.Text;
String name = txtName.Text;
String tel = txtTel.Text;
String add = txtAdd.Text;
String SqlQuery = #"INSERT INTO [Table]
VALUES(#id, #name, #tell, #add)";
using (SqlConnection con = new SqlConnection(conString))
using (SqlCommand cmnd = new SqlCommand(SqlQuery, con))
{
con.Open();
cmnd.Parameters.Add("#id", SqlDbType.NVarChar).Value = id;
cmnd.Parameters.Add("#name", SqlDbType.NVarChar).Value = name;
cmnd.Parameters.Add("#tel", SqlDbType.NVarChar).Value = tel;
cmnd.Parameters.Add("#add", SqlDbType.NVarChar).Value = add;
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Sucessfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error occurred while saving", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
When I run this code, there is an error message
Must declare scalar variable #tell
Why do I get an error message like this? Is my code wrong? Can you please help me to get rid of this problem?
This is the error message which I get:
Error message.
You'll need to change the 3rd parameter.
Change cmnd.Parameters.Add("#tel", SqlDbType.NVarChar).Value = tel;
To
cmnd.Parameters.Add("#tell", SqlDbType.NVarChar).Value = tel;
The parameter name is different in your declared sql
There is a typo it seems, it should be #tell (notice double l).
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 7 years ago.
Improve this question
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("IF (select 1 from PRODUCT where PRODUCT_NAME=" + Master_product_txt.Text + ")=1
PRINT 'ALREADY AVAILABLE'
ELSE
Insert into PRODUCT(PRODUCT_NAME) Values('" + Master_product_txt.Text + "')
GO", objsqlconn);
objcmd.ExecuteNonQuery();
MessageBox.Show("Details Successfully Added!!!");
I'm trying check the data base values before insert the value, I've wrote query for it, it's working in sql server environment, I could not able to implement same thing in Visual Studio
go is a SSMS (SQL Server Management Studio) statement, it won't work from C#
use parameters to avoid SQL injection
it is unusual to use the Hungarian obj prefix in C#
A quick try at a better version:
var cmd = new SqlCommand(#"
IF NOT EXISTS (SELECT * FROM PRODUCT WHERE PRODUCT_NAME = #NAME)
BEGIN
INSERT INTO PRODUCT (PRODUCT_NAME) VALUES (#NAME)
END
", sqlconn);
cmd.Parameters.AddWithValue("#NAME", Master_product_txt.Text);
cmd.ExecuteNonQuery();
SqlCommand objcmd = new SqlCommand("SELECT 1 from PRODUCT WHERE PRODUCT_NAME=#NAME" , objsqlconn);
//NVarChar
cmd.Parameters.Add("#NAME", SqlDbType.NVarChar,20).Value = Master_product_txt.Text;
objsqlconn.Open();
readr = SelectCommand.ExecuteReader();
if (!readr.HasRows)
{
`// code to insert values here.
}`
PRINT 'ALREADY AVAILABLE' will not work here.For capturing print statement message you have to add an event handler to the InfoMessage event on the connection.And use parametrized query where ever possible. ;)
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 7 years ago.
Improve this question
I'm facing this error when I want to connect to the SQL Server 2008 database.
ERROR:
System.InvalidOperationException: ExecuteNonQuery: Connection property, has not been initialized.
at System.Data.Sq1Client.Sq1Command.ValidateCommand(String method, Boolean async)
at System.Data.Sq1Client.Sq1CommandinternalExecuteNonQuery(TaskCompletionS ource'1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.Sq1Client.Sq1Command.ExecuteNonQuery()
at WindowsFormsApplication2.Form1.create_Click(Object sender, EventArgs e) in C:\Users\admin\Documents\Visual Studio 201CAProjects\WindowsFormsApplicationaWindowsFormsApplicationaForm1.cs line 127
SqlCommand cmd = new SqlCommand();
cmd.CommandText="insert into dbo.Student_Record
(
ID,
Name,
[Father's CNIC],
[Father's Name],
CNIC
)
values
('BCSF11A003',
'Zargham Nazeer Malik',
'35202-2953923-3',
'Khalid Nazeer Malik',
'35202-2235390-5')";
cmd.ExecuteNonQuery();
con.Close();
}
You're not adding a connection to your command:
cmd.Connection = con;
The error simply means you are trying to use SqlCommand before assigning a connection to it.
Please check. If you will include code part here then it will be more useful.
This code should work and solve your problem:
using(SqlConnection con = new SqlConnection("CHANGE_THIS_TO_YOUR_CONNECTIONSTRING")){
SqlCommand cmd = con.CreateCommand();
cmd.CommandText="insert into dbo.Student_Record(ID,Name,[Father's CNIC],[Father's Name],CNIC) values ('BCSF11A003','Zargham Nazeer Malik','35202-2953923-3','Khalid Nazeer Malik','35202-2235390-5')";
cmd.ExecuteNonQuery();
}
You have to change CHANGE_THIS_TO_YOUR_CONNECTIONSTRING to a connectionstring.
See: https://www.connectionstrings.com/sql-server/ for how to find out a correct string.
I would do this to include all the usual best practices:
// define the query - you should use **parameters** to avoid SQL injection
string query = "insert into dbo.Student_Record(ID, Name, [Father's CNIC], [Father's Name], CNIC) values ('BCSF11A003', 'Zargham Nazeer Malik', '35202-2953923-3', 'Khalid Nazeer Malik', '35202-2235390-5');";
// define connection string - typically read from config
string connectionString = "";
// create connection and command objects, set the "conn" connection on the "cmd" object in the constructor
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// open connection, execute command, close connection
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
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!!");
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My code needs to save all the information captured in the WinForm Vendita.
I'm using the following code but it doesn't save the information in the DB and gives me an error indicating a data type mismatch in the criteria expression.
I am using the following code:
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbCommand cmd2 = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbCommand cmd3 = new System.Data.OleDb.OleDbCommand();
cmd1.CommandType = System.Data.CommandType.Text;
cmd2.CommandType = System.Data.CommandType.Text;
cmd1.CommandText = "INSERT INTO FattureVoci ([IDVoce],[CodiceArticolo],[Descrizione],[Quantita],[PrezzoUnitario]) VALUES (#Id,#Prod,#Descr,#Qta,#Prezzo)";
cmd2.CommandText = "INSERT INTO Fatture ([Intestatario],[PartitaIVA]) VALUES (#Intest,#Iva)";
cmd1.Parameters.AddWithValue("#Prod", this.Prodotto.Text);
cmd1.Parameters.AddWithValue("#Iva", Convert.ToInt32(this.PartitaIVA.Text));
cmd1.Parameters.AddWithValue("#Descr", this.Descrizione.Text);
cmd1.Parameters.AddWithValue("#Qta", Convert.ToInt32(this.Qta.Text));
cmd1.Parameters.AddWithValue("#Intest", this.Intestatario.Text);
cmd1.Parameters.AddWithValue("#Id", Convert.ToInt32(this.id.Text));
cmd1.Parameters.AddWithValue("#Prezzo", Convert.ToInt32(this.Prezzo.Text));
cmd1.Connection = conn;
conn.Open();
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
conn.Close();
}
Iva and Interest belong to cmd2 instead of cmd1. Change this:
cmd1.Parameters.AddWithValue("#Iva", Convert.ToInt32(this.PartitaIVA.Text));
cmd1.Parameters.AddWithValue("#Intest", this.Intestatario.Text);
To:
cmd2.Parameters.AddWithValue("#Iva", Convert.ToInt32(this.PartitaIVA.Text));
cmd2.Parameters.AddWithValue("#Intest", this.Intestatario.Text);
Also, you are using OleDb, so probably Ms Access: you should provide the parameters in the correct order.