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();
Related
I'm trying to prevent SQL injections. Am I doing this right? (I'm using MS Access.) Should I still use sqlparameter?
OleDbParameter[] myparm = new OleDbParameter[2];
myparm[0] = new OleDbParameter("#UserID", UserName.Text);
myparm[1] = new OleDbParameter("#Password", encode);
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
Close!
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#UserID", UserName.Text);
cmd.Parameters.AddWithValue("#Password", encode);
The parameters are part of the command object and you use the Parameters.AddWithValue method to set the parameter values to what you have defined in the query string.
By the way, you should be using using statements to encapsulate some of your objects, here is what I typically do:
using (OleDbConnection conn = new OleDbConnection(_connStr))
using (OleDbCommand = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT ...";
cmd.Parameters.AddWithValue(...);
cmd.ExecuteReader();
//...
}
That way you don't have to worry about cleaning up resources if something goes wrong inside or closing the connection when you are done.
For some reasons, I am unable to establish a data connection using my connection string. I was doing with the below code
var connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection(connectionString);
cmd.Connection = connectionString;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = " dbo.SelectAll";
SqlParameter param = new SqlParameter("#tradeDate","201401");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
But for some reasons when I am initializing the connection property to my command using cmd.Connection = connectioString, is is throwing an exception as follows
Cannot implicitly convert type 'string' to
'System.Data.SqlClient.SqlConnection'
You're confusing the connection string needed to connect to the database and the actual SqlConnection.
try this (for your specific code):
cmd.Connection = con;
According to MSDN here is a proper example:
private static void CreateCommand(string queryString, string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Link to original article: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx
I think you need just
cmd.Connection = con;
You are try to do set your SqlCommand.Connection property with your connection string. But this property is for specify your SqlConnection object, not your connection string.
From documentation;
Gets or sets the SqlConnection used by this instance of the
SqlCommand.
And since there is no implicit conversation from SqlConnection to string, that's why you get compile time error.
As a side note, use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
...
...
}
or you can use SqlConnection.CreateCommand() method to create your SqlCommand associated your SqlConnection inside your using statement like;
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
...
...
}
I have this code to execute a stored procedure (Update SP) in ASP.Net, unfortunately record is not updating when I run the code.
This is my code:
using (SqlConnection sqlConnection = Connt.GetConnection(TblName))
{
sqlConnection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(SqlScript, sqlConnection))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.AddRange(SqlParam);
}
}
Where SqlScript is the variable for the stored procedure name and SqlParam is the parameters.
Please help me figure out what is wrong with my code.
Hi you can try something like this
SqlConnection sqlConnection = new SqlConnection();
SqlCommand sqlCommand = new SqlCommand();
sqlConnection.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True";
public void samplefunct(params object[] adparam)
{
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "SPName";
sqlCommand.Parameters.Add("#param1", SqlDbType.VarChar).Value = adparam[0];
sqlCommand.Parameters.Add("#param2", SqlDbType.VarChar).Value = adparam[1];
sqlCommand.Parameters.Add("#Param3", SqlDbType.VarChar).Value = adparam[2];
sqlCommand.ExecuteNonQuery();
}
Try:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
With a Param:
command.Parameters.Add(new SqlParameter("#ID", 123));
I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections
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.