SQL query is not being executed in C# - c#

I have a SQL query and I want to execute it in C# on a button click, but when I click the
button the database is not being affected:
private void button1_Click(object sender, EventArgs e) {
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
con.Close();
}

The code you want is this:
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
String sql = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
cmd.ExecuteNonQuery();
}

Add cmd.ExecuteNonQuery after setting the command text.

You need to actually execute the query (try ExecuteNonQuery).
You're currently opening a connection, setting the statement to execute, then just closing the connection.

Related

Unable to insert values in sql server local db using c#

I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.

How do inject from Asp.net to a SQL database?

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

use SqlConnection, but can not find the SQL database

My database layout looks like this:
-App_Data
-Database.mdf
-Database_log.ldf
and this is my code:
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
SqlConnection myConn = new SqlConnection(strConn);
myConn.Open();
String strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
myConn.Close();
When I test in browser, however, it sends an error message and stops in this code "myConn.Open();"can't find server
Why is this happening?
change
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
to
string strConn = #"Data Source=.\SQLExpress;Initial Catalog=Database;Integrated Security=True";
Attach a database file, located in the data directory, on connect to a
local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|dbfilename.mdf;Database=dbname;
Trusted_Connection=Yes;
so your connection string should be similar to below, replace database name corectly
string strConn =#"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database.mdf;Database=dbname; Trusted_Connection=Yes;";
using (SqlConnection myConn = new SqlConnection(strConn))
{
string strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
myConn.Open();
using(SqlCommand myCommand = new SqlCommand(strSQL, myConn))
{
myCommand.ExecuteNonQuery(); // you haven't execute the insert
}
}

exception thrown while connecting to database: connection property has not been initialized

I am trying basic database insert and this code is waht I am running in visual studio 2010:-
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
where am I wrong?
You created a connection and opened it, but you did not associate it with the SqlCommand. You can do this a couple of ways, either in the constructor of the SqlCommand or through the Connection property of the SqlCommand.
Additionally, you should use parameterized queries to prevent SQL Injection attacks. I'd also recommend putting the SqlConnection in a using block to ensure it is closed and properly disposed of. Putting all of that together gives you something like this:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("insert into names values(#name)", conn);
// Alternatively, you could do cmd.Connection = conn if you didn't pass
// the connection object into the SqlCommand constructor
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.ExecuteNonQuery();
}
}
You did not assign the connection to the command object. try:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
cmd.Connection = conn; // <- this is the missing line
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

Connection string not working in C# windows application

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())
{
...
...
}

Categories

Resources