private void btnSave_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStaffID.Text = "";
txtStaffID.Focus();
}
else
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',#img)";
if (con.State != ConnectionState.Open)
con.Open();
cm = new SqlCommand(Query, con);
cm.Parameters.Add(new SqlParameter("#img", img));
int x = cm.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Successfully Saved!");
}
}
catch (Exception ex)
{
con.Close();
MessageBox.Show(ex.Message);
}
}
This is my code i don't understand why I'm getting this error:
ExecuteReader:Connection Property has not been initialized.
I'm making a save button where the Staffid will be checked first if already.
Before executing the command, you need to say which connection is to be used. In your case, it is:
cm.Connection = con;
Take a note that, include this line of code after opening the connection and after creating the instance of SqlCommand.
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
cm.Connection = con; //Assign connection to command
You didn't assign connection to SqlCommand used in the reader
The error message is clear enough, You have to assign the connection for the Command, either through assignement or through the constructor, That is:
cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader rdr = cm.ExecuteReader();
Or else you can use the constructor to initialize the command like this:
cm = new SqlCommand(CheckID,con);
Hope that you are aware of these things since you ware used it correctly in the else part of the given snippet
Make sure that you assign the SqlConnection to your Command-Object. You can do this via Constructor or Property:
con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
Further I would recommend you to use a using-block to make sure that the Command and Connection gets destroyed after using it.
using (var con = new SqlConnection())
{
using (var cm = new SqlCommand())
{
}
}
Related
I Inserted Data to ComboBox using Folloowing Code in FormLoad Block
try
{
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
it does the Job. in the Form You can Create a Category and Delete By Selecting The Name of the category from ComboBox Here is a ScreenShot the Form. I used the following code to Delete and Load the items to ComboBox after Deleting.
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedItem.ToString() + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully deleted " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
catch
{
StatusLabel.Text = "An Error occured while deleting " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
finally
{
try
{
SelectCategoryComboBox.Items.Clear();
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
code for Creating new item Given below
if (CategoryNameText.Text == "")
{
StatusLabel.Text = "You have to provide a name to create a category";
}
else
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully created " + CategoryNameText.Text + " Category";
try
{
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = "An Error Occured while Loading Data!";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
CategoryNameText.Focus();
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = ("An ERROR occured While creating category!");
}
finally
{
CategoryNameText.Text = "Enter Category Name";
}
}
}
This Code Deletes Items Perfectly.But If I delete an Item Which is Already in the ComboBox, it does the Job i.e it deletes and Load the Remaining items to ComboBox.but, if I Created an Item,and Deleted it Before Closing the Form, it deletes the item.But Fails to Load the remaining items.it shows all the items already exist in the ComboBox Before Deleting. Would be a great help if you can help me solve this problem. Here SelectCategoryComboBox is the Name of the ComboBox.
I find the problem occur in the following sentence.
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
I have two solutions.
First, Please set the Allow nulls for other field.
Like the following:
Second, you can use the following code to replace the original code.
string query = string.Format("INSERT INTO Student(CategoryName, CategoryId, Age) VALUES('{0}','{1}','{2}')",textBox1.Text,textBox2.Text,textBox3.Text);
I found What went Wrong...
Change Following Code
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
To
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string squery = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(squery, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
it Worked for me.
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
This code displays an error like this:
System.InvalidOperationException. ExecuteNonQuery: Connection property has not been initialized.
You need to tell your sql command that use this connection(con) to execute the command(cmd).so use an overloaded constructor of the SqlCommand class that takes 2 parameters(cmdText, connection).
SqlCommand cmd = new SqlCommand("update Students set RegNo='" +
RegNo"',Name='" + Name.Text + "',Address=" + Address.text, con);
But it is also possible, to create an instance of SqlCommand class using the parameter less constructor, and then later specify the command text and connection, using the CommandText and Connection properties of the SqlCommand object as shown below.
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
You can use the using statement where the resources are automatically disposed.We don't have to explicitly call Close() method, when using is used. The connection will be automatically closed for us.
int result;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text, con);
con.Open();
result = cmd.ExecuteNonQuery();
}
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
To try to use as following sample code
string constr ="Data Source=localhost;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=1111"
SqlConnection con = new SqlConnection(constr);
I think , in the SQL Command you need to assign the connection
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Student set Name='" + Name.Text + "',Address='" + Address.Text + "'where RegNo=" + RegNo.Text);
cmd.Connection = con;//adding this line my error solved
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
I changed my code like above.
Error An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. How to fix it?
Image: http://i.stack.imgur.com/7Sibc.png
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand sc = new SqlCommand("select Title from TongHopDB", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Load(reader);
cboxDB.ValueMember = "Title";
cboxDB.DisplayMember = "Title";
cboxDB.DataSource = dt;
conn.Close();
}
private void cboxDB_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "Select Title, Post from TongHopDB where Title = " + cboxDB.SelectedValue.ToString(); // câu query có thể khác với kiểu dữ liệu trong database của bạn
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sdr = cmd.ExecuteReader();
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
sdr.Close();
sdr.Dispose();
conn.Close();
conn.Dispose();
}
string sql = "Select Title, Post from TongHopDB where Title = '" + cboxDB.SelectedValue.ToString()+"'";
However I strongly suggest to use parameters:
string sql = "Select Title, Post from TongHopDB where Title = #Title";
cmd.Paramaters.Add( "#Title",cboxDB.SelectedValue.ToString());
I strongly suspect your Title is character typed, that's why it needs to used with single quotes as;
where Title = '" + cboxDB.SelectedValue.ToString() + "'";
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader objects automatically instead of calling Close or Dispose methods manually.
using(var conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7"))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Title, Post from TongHopDB where Title = #title";
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = cboxDB.SelectedValue.ToString();
// I assumed your column type is nvarchar.
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
if(dr.Read())
{
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
}
}
}
cboxDB.SelectedValue is Apple according to the error shown in your screen shot. Your SQL statement is saying in plain English:
Select Title(column) and Post(column) from TongHopDB(table) where Title(column) equals Apple(column)
Apple is not a valid column!
While it would work to simply add single quotes around the value of cboxDB, you should use parameters instead of concatenating a string. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
I have tried search for an ID in an MySQL table and return the associated string column which holds the URL.
But The Downloader always tells me the link format is wrong.
This is my method:
public string URL(string ID)
{
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;");
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID = '" + ID + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
return reader.ToString();
}
And here the downloader:
private void button1_Click(object sender, EventArgs e)
{
sql_reader sql_reader = new sql_reader();
if (!Directory.Exists("Downloads"));
{
Directory.CreateDirectory("Downloads");
}
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text)), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
textBox1 is the Box where I type in the ID.
1. you need to call Read() function before fetching the records from MySqlDataReader Object
2. you have to specify the column name while accessing the records.
Example:
String result="";
MySqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
result=reader["columnname"].ToString();
3. I would suggest you to use Parametrised Queries to avoid SQL injection Attacks.
Example:
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =#ID;");
cmd.Parameters.AddWithValue("#ID",ID);
4. dipose the MySqlCommand,MySqlConnection and MySqlDataReader Objects properly. you can use using{} block to dipose them cleanly.
Complete Code
public string URL(string ID)
{
String result="";
using(MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;"))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =#ID;"))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#ID",ID);
using(MySqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
result=reader["string"].ToString();
else
result="";//you can customize here
}
}
}
return result;
}
Solution 2:
Replace This Statement:
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text)), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
With this:
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text),UriKind.Absolute), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.