Im trying to add items in the comboBox (cmbInstructor) namely the last names (instructorLN) however, my code does not seem to work. Any ideas on where I went wrong?
private void cmbInstructor_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(mycon);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM instructor WHERE instructorType ='" + labelClass.Text + "'", conn);
string instructorLN = "";
conn.Open();
MySqlDataReader myReader = null;
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
instructorLN = myReader["instructorLN"].ToString();
}
cmbInstructor.Items.Add(instructorLN);
}
As far as I can see, you are adding only last value that your SELECT returns.
Move your
cmbInstructor.Items.Add(instructorLN);
line into to the while statement as;
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
By the 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 connection and command and reader automatically.
using(var conn = new MySqlConnection(mycon))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM instructor WHERE instructorType = #type";
cmd.Parameters.Add("#type", labelClass.Text);
conn.Open();
using(var myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
}
}
Related
Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...
Hello trying to delete several rows of the table according to a condition, however i need some help with it, basically i want to delete all rows, while the condition is true and then stop and leave the rest untouched.
EDIT: Regarding the comments i apologize, im fairly new to programming, sorry if not doing things correctly im new to this website as well.
private void button1_Click(object sender, EventArgs e)
{
string varsql2check = "";
do{
SqlConnection conn = new SqlConnection(#"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd");
conn.Open();
string varsql = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' "; //sql query
SqlCommand cmd = new SqlCommand(varsql, conn);
SqlDataReader dr = cmd.ExecuteReader();
} while(varsql2check = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120);");
dr.Close();
conn.Close();
}
What you need to do is:
private void button1_Click(object sender, EventArgs e)
{
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' ";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120)";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
}
}
}
}
while (check);
}
Generally what I have done by editing your code is:
Add the using statement in order to release the resources from the established connections.
You should be using the returned types from the exeqution of the queries. The ExecuteNonQuery() will return the numbers of rows affected, in our case we are particularly interested in the rows returned from the select statement after the delete query. We create a reader and depending of the number of rows, in our case we are only interested if there are rows or no, branch accoringly. If we get no rows from the select (everything is deleted) we just continue, if we get nothing (reader.HasRows returns false) we repeat the delete query and check again.
Simple as that.
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 am trying to display some values in textboxes from a database by selecting a site ID from a drop down list. The drop down list is working perfectly and showing the site IDs that are stored in the database. While running this application it shows an error:
Execute Reader requires an open and available Connection. The connection's current state is closed.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOption();
}
}
private void LoadOption()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(#"connectionString");
using (con)
{
SqlDataAdapter adpt = new SqlDataAdapter("SELECT Site_ID FROM tbl_Survey1", con);
adpt.Fill(dt);
ddlSiteID.DataSource = dt;
ddlSiteID.DataTextField = "Site_ID";
ddlSiteID.DataValueField = "Site_ID";
ddlSiteID.DataBind();
ddlSiteID.Items.Insert(0, new ListItem("--Select ID--", ""));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"connectionString");
string selectID = ddlSiteID.SelectedValue;
SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con);
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
Source:
<asp:DropDownList ID="ddlSiteID" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlSiteID_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="txtSiteName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSiteAddress" runat="server"></asp:TextBox>
The error explains all. Your connection is closed when you call ExecuteReader. But I suppose that you are asking why?.
You think that, because you have already loaded the dropdown, then you could execute your reader without problems. But, unfortunately, the SqlDataAdapter has its own behavior when working with the connection.
From MSDN SqlDataAdapter.Fill
The Fill method retrieves rows from the data source using the SELECT
statement specified by an associated SelectCommand property. The
connection object associated with the SELECT statement must be valid,
but it does not need to be open. If the connection is closed before
Fill is called, it is opened to retrieve data, then closed. If the
connection is open before Fill is called, it remains open.
So you just need to open the connection in this way
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
string selectID = ddlSiteID.SelectedValue;
using(SqlConnection con = new SqlConnection(#"connectionString"))
using(SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
....
}
}
}
P.S. Remember to keep always your disposable objects like the connection, command and reader inside an Using block to be sure that they are closed and disposed correctly also in case of exceptions
You're missing in the second method an explicit call to open your connection:
con.Open();
Also, you don't dispose of said connection -- be careful with that. Use usings for anything that implements IDisposable:
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"connectionString"))
{
con.Open();
string selectID = ddlSiteID.SelectedValue;
using (SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
}
You should open your connection by calling con.Open() before calling ExecuteReader in ddlSiteID_SelectedIndexChanged method. And don't forget to close it in the end.
This means your code may look like
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
using(var con = new SqlConnection(#"connectionString"))
{
string selectID = ddlSiteID.SelectedValue;
using (var cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
finally
{
con.Close();
}
}
}
}
try this In SelectedIndexChanged event of DropDown.
SqlCommand requires Connection to be open
SqlConnection con = new SqlConnection(#"connectionString");
string selectID = ddlSiteID.SelectedValue;
SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con);
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
con.open
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
con.close();
Check if your connection is open or not.
if (con != null && con.State == ConnectionState.Closed)
{
con.Open();
}
I'm trying to make a login facility for Windows Forms Application project. I'm using Visual Studio 2010 and MS Sql Server 2008.
I referenced this article:
http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Here is my database table named user:
I have TextBox1 for user name , TextBox2 for user password and Button1 for starting login process. Here is my code for Button1_Click method:
private void button1_Click(object sender, EventArgs e)
{
string kullaniciAdi; // user name
string sifre; // password
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
myConn.Open();
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from user where u_name='" + textBox1.Text + "';");
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
myConn.Close();
}
I don't have much experience with C# but i think i'm missing something small to do it right. Below i share exception message that i catched. Can you show me what i'm missing? (line 33 is myReader = myCommand.ExecuteReader();)
Considerin given answers, i updated my try block as in below but it still does not work.
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where u_name=#user");
SqlCommand myCommand = new SqlCommand(myQuery, myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
if (textBox2.Text.Equals(sifre))
{
Form2 admnPnl = new Form2();
admnPnl.Show();
}
}
After changing whole code as below by sine's suggestion, screenshot is also below:
And i think, somehow i cannot assign password in database to the string sifre.
code:
string sifre = "";
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "EKS";
builder.UserID = "sa";
builder.Password = "123";
using (var conn = new SqlConnection(builder.ToString()))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if (tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
if (textBox2.Text.Equals(sifre))
{
try
{
AdminPanel admnPnl = new AdminPanel();
admnPnl.Show();
}
catch (Exception y)
{
MessageBox.Show(y.ToString());
}
}
else
{
MessageBox.Show("incorrect password!");
}
}
}
}
User is a reserved keyword in T-SQL. You should use it with square brackets like [User].
And you should use parameterized sql instead. This kind of string concatenations are open for SQL Injection attacks.
string myQuery = "select u_password from [user] where u_name=#user";
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Try to put user into [ ] because it is a reseved Keyword in T-SQL and use Parameters, your code is open to SQL-Injection!
private void button1_Click(object sender, EventArgs e)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "servername";
builder.InitialCatalog = "databasename";
builder.UserID = "username";
builder.Password = "yourpassword";
using(var conn = new SqlConnection(builder.ToString()))
{
using(var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if(tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
}
}
}
}
USER is a reserved word in T-SQL
Try putting [] around reserved words.
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
user is a keyword.
Change it to something like
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
Futher to that I recomend you have a look at Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
User is a reserved keyword in SQL, you need to do this:
select u_password from [user] where u_name=#user
And as ever, with basic SQL questions, you should always use parameterised queries to prevent people from running any old commands on your DB via a textbox.
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);