I created a simple SQL database that has one table, tblCustomerInformation, and three columns :
FirstName,
LastName,
and Email.
I'm attempting to update it however when I run the code that I listed below the program does nothing.
It doesn't crash and give me errors it just does nothing.
I'm fairly certain that my UPDATE statement is correct. I'm not sure why this isn't working at this point.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE (FirstName = #fn)";
//cmd.Parameters.Add("#ln", SqlDbType.NVarChar);
//cmd.Parameters["#ln"].Value = txtLastName.Text;
//cmd.Parameters.Add("#em", SqlDbType.NVarChar);
//cmd.Parameters["#em"].Value = txtEmail.Text;
//cmd.Parameters.Add("#fn", SqlDbType.NVarChar);
//cmd.Parameters["#fn"].Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Use this. The arrangement of cmd.Parameters... code should not be jumbled. Base it on the arrangement in your query.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE FirstName = #fn";
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Have encountered this kind of error once.
Related
I have a hard time figuring out what is wrong about my code. The purpose is to take data from a registering form in ASP to my user data columns in my SQL database.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin
values(#UserName,#Password)";
SqlConnection cnn = new SqlConnection(cmd);
SqlCommand cmd2 = new SqlCommand(cmd, cnn);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
You're using the connection string in the connection variable but the variable you're passing to SqlCommand is cnn which doesn't have a valid connection string associated with it.
I've cleaned up your code and made use of using block to ensure the correct manner of disposing the object. Please see below:
string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
string query = "insert into UserLogin values(#UserName, #Password)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd.Parameters.AddWithValue("#Password", PasswordBox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have two SqlConnection variable and assigning wrong one in the SqlCommand. The working code will be:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin values(#UserName, #Password)";
SqlCommand cmd2 = new SqlCommand(cmd, connection);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
string _connStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\James JJ\Desktop\jj\Web App\Website\App_Data\LoginDB.mdf;Integrated Security=True";
string _query = "INSERT INTO [RegistrationTable] (Email, Password, HomeAddress, PostalCode, Gender) VALUES (#email, #password, #haddress, #postalcode, #gender)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#email", Emailtxt.Text);
comm.Parameters.AddWithValue("#password", Passwordtxt.Text);
comm.Parameters.AddWithValue("#homeaddress", hAddresstxt.Text);
comm.Parameters.AddWithValue("#postalcode", Postaltxt.Text);
comm.Parameters.AddWithValue("#gender", gender);
conn.Open();
comm.ExecuteNonQuery();
Response.Redirect("RegistrationSuccess.aspx");
}
}
I really tried all the solutions on the net but I still keep getting errors.
Error shows : ExecuteScalar: Connection property has not been
initialized and exists = (int)cmd.ExecuteScalar() > 0;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (#UserID,#FName, #LName, #PhoneNo, #Address, #Email, #UserName, #Password, #Points, #Role)");
try
{
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#FName", tbFName.Text);
cmd.Parameters.AddWithValue("#LName", tbLName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#Address", tbAddress.Text);
cmd.Parameters.AddWithValue("#Email", tbEmail.Text);
cmd.Parameters.AddWithValue("#UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("#Password", tbPassword.Text);
cmd.Parameters.AddWithValue("#Points", Points);
cmd.Parameters.AddWithValue("#Role", Role);
connection.Open();
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}
}
What should be the correct way to declare the connection first because I tried to put it before but I'm having problems with the cmd.
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
You need to assign the connection to the command in your last example
So within your using statement add:
cmd.Connection = connection;
Additionally you don't need:
SqlCommand cmd;
as the command is created within the context of that using statement.
It's also considered good practice to wrap the Connection context within a using statement to ensure the actual connection get's disposed / closed correctly.
Try this,
using (SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"))
{
connection .Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection );
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
bool exists = (int)cmd.ExecuteScalar() > 0;
}
You didn't specified connection to command. Secondly you have to open connection.
Update: Complete Code
try
{
string connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
bool exists = false;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection .Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection );
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (#UserID,#FName, #LName, #PhoneNo, #Address, #Email, #UserName, #Password, #Points, #Role)", Connection);
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#FName", tbFName.Text);
cmd.Parameters.AddWithValue("#LName", tbLName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#Address", tbAddress.Text);
cmd.Parameters.AddWithValue("#Email", tbEmail.Text);
cmd.Parameters.AddWithValue("#UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("#Password", tbPassword.Text);
cmd.Parameters.AddWithValue("#Points", Points);
cmd.Parameters.AddWithValue("#Role", Role);
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
//Do something
}
finally
{
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}
SQL command should have a overload which takes an initiated connection
Use SqlCommand constructor that takes connection as second argument. Next you have to open it before executing command and after that close it.
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
connection.Open();
exists = (int)cmd.ExecuteScalar() > 0;
connection.Close();
}
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO user(Firstname,Lastname,Email,Pass,Type)
values(#first,#last,#email,#pass,#type)",con);
cmd.Parameters.Add("#first",SqlDbType.NVarChar).Value = txtfirst.Text;
cmd.Parameters.Add("#last",SqlDbType.NVarChar).Value = txtlast.Text;
cmd.Parameters.Add("#email",SqlDbType.NVarChar).Value = txtemail.Text;
cmd.Parameters.Add("#pass",SqlDbType.NVarChar).Value = txtpass.Text;
cmd.Parameters.Add("#type",SqlDbType.NVarChar).Value = "customer";
cmd.ExecuteNonQuery();
con.Close();
what is the problem with my syntax it says "Incorrect syntax near the keyword 'user'."
you should escape the table name user with delimited identifiers,
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(#first,#last,#email,#pass,#type)",con);
SQL Server Reserved Keywords
SQL Server Delimited Identifiers
UPDATE 1
Refractor your code by
using using statement to properly dispose objects
using Try-Catch block to properly handle exceptions
code snippet:
string _connStr = "connectionString here";
string _query = "INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values (#first,#last,#email,#pass,#type)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#first", txtfirst.Text);
comm.Parameters.AddWithValue("#last", txtlast.Text);
comm.Parameters.AddWithValue("#email", txtemail.Text);
comm.Parameters.AddWithValue("#pass", txtpass.Text);
comm.Parameters.AddWithValue("#type", "customer");
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(SqlException ex)
{
// other codes here
// do something with the exception
// don't swallow it.
}
}
}
AddWithValue
Add (recommended one)
USER is a reserved keyword on SQL Server.
You should use your table name with brackets [] like;
INSERT INTO [user]
You can try like;
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(#first,#last,#email,#pass,#type)",con);
cmd.Parameters.AddWithValue("#first", txtfirst.Text);
cmd.Parameters.AddWithValue("#last", txtlast.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#pass", txtpass.Text);
cmd.Parameters.AddWithValue("#type", "customer");
cmd.ExecuteNonQuery();
con.Close();
And also like #JW said, it is always a good approach to using them in a try-catch statement.
Best Practices of Exception Management
I'm trying to insert a textbox value to a database table called site_list.
The site_list table contains two columns id and site_name, id set to auto increment
This is the code I'm trying and when it execute there is no error, but the data is not showing up in the table
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|scraper_db.mdf;";
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name) "
+ " VALUES (#site_name)", conn);
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
conn.Open();
addSite.ExecuteNonQuery();
conn.Close();
Any help would be appreciated.
Regards
Edit:
This code started to work
string connstring = "Data Source=.\\SQLExpress;"+
"Integrated Security=true;"+
"User Instance=true;"+
"AttachDBFilename=|DataDirectory|scraper_db.mdf;"+
"Initial Catalog=scraper_db";
using (SqlConnection connection = new SqlConnection(connstring))
{
connection.Open();
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name)"+
"VALUES (#site_name)", connection);
addSite.Parameters.AddWithValue("#site_name", textBox1.Text);
addSite.ExecuteNonQuery();
connection.Close();
}
as people suggests, try creating the database on the server (it will be even easier to handle using Sql Management Studio).
Once that's done, try the following (just tested and it works):
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO site_list (site_name) VALUES (#site_name)", conn);
addSite.Parameters.AddWithValue("#site_name", "mywebsitename");
addSite.Connection.Open();
addSite.ExecuteNonQuery();
addSite.Connection.Close();
}
try
{
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)\SQLEXPRESS;database=Inventory;Data Source=localhost\SQLEXPRESS;"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO Creation (Name,Product,Quantity,Category) VALUES (#Name,#Product,#Quantity,#Category)", conn);
addSite.Parameters.AddWithValue("#Name", textBox1.Text);
addSite.Parameters.AddWithValue("#Product", textBox2.Text);
addSite.Parameters.AddWithValue("#Quantity", textBox3.Text.ToString());
addSite.Parameters.AddWithValue("#Category", textBox4.Text);
thisConnection.Open();
addSite.ExecuteNonQuery();
}
}
catch
{
thisConnection.Close();
}
try this out :
string sql = String.Format("INSERT INTO site_list (site_name) VALUES('{0}')", myTextBox.Text);
using(SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.open();
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.ExecuteNonQuery();
}
}
Good luck
Try storing your textbox value in a variable. As in:
#stringname = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = #stringname;
(IMPORTANT! the # in #stringname is not necessary, but protects you against hackers!)
This code has worked wonders for me.
My apologies. The answer I gave previously will not work because the variable name used in the insert command (in your case #site_name) must match the variables used in your sqlcommand. As in:
#site_name = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
Sorry for the confusion I might have caused.