I try to call function to select data from database,coz it will more efficient and i don't like to open connection and execute reader every time,have any solution can do like that?
this is my first method to select data from database,but will hit sql injection problem
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
lblAns.Text = myClass.getdata("Table1", "Student", "Student = '" + TextBox1.Text + "'");
}
public string getdata(string table,string field,string condition)
{
SqlDataReader rdr;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
string sql = "select " + field + " from " + table + " where " + condition;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
this is my second method but will hit error (ExecuteReader requires an open and available Connection. The connection's current state is closed.) at line (rdr = cmd.ExecuteReader();)
public string getdata(SqlCommand command,SqlConnection conn)
{
SqlDataReader rdr;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = command;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
public SqlConnection conn()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
return conn;
}
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
string strSql;
strSql = "Select student from Table1 where student=#stu";
SqlCommand command = new SqlCommand(strSql, myClass.conn());
command.Parameters.AddWithValue("#stu", TextBox1.Text);
myClass.getdata(command, myClass.conn());
}
have solution can use 1st method but will not hit the sql injection problem?
Use ALWAYS the second solution. The only way to avoid Sql Injection is through the use of parameterized queries.
Also fix the error on the second example. You don't associate the connection to the command, also it is a bad practice to keep a global object for the connection. In ADO.NET exist the concept of Connection Pooling that avoid the costly open/close of the connection while maintaining a safe Handling of these objects
public string getdata(SqlCommand command)
{
// Using statement to be sure to dispose the connection
using(SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
return msg;
}
}
return "false";
}
Related
I am working on a windows form project with a sql database I want to write some data but I couldn't. (the code doesn't give any error however no data is written.
The code below is the place where I want to write the data:
public static string stringConnection = #"Data Source=(localdb)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\POS.mdf; Integrated Security=True";
try
{
mySql = string.Empty;
mySql += "INSERT INTO Journal (Date) VALUES (" + "'"+ caisse + "'"+")" ;
connection.exsql(mySql);
}
catch(Exception exx)
{
MessageBox.Show(exx.ToString());
}
and here is the connection.exsql method:
public static void exsql(string sql)
{
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = default(SqlDataAdapter);
try
{
connection.ConnectionString = stringConnection;
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
connection.Close();
//connection = null;
}
catch (Exception ex)
{
MessageBox.Show("Fatal sql error: " + ex.Message, "Sql Server connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You want to use the sqlCommand and execute .ExecuteNonQuery() to do an INSERT or UPDATE.
More info here.
Also, use parameterization (an example is shown in the link above), otherwise, you open yourself up to SQL injection and your code will fail if your variable contains a single quote.
Less code
private bool exsql(string query)
{
using(var conn = new SqlConnection(ConnectionString.path))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
return command.ExecuteNonQuery() == 0 ? false : true;
}
}
SqlConnection con;
SqlCommand cmd;
public bool exsql(string query)
{
try {
con = null;
con = new SqlConnection(ConnectionString.path);
cmd = new SqlCommand(query, con);
con.Open();
var rowEffected = cmd.ExecuteNonQuery();
con.Close();
if(rowEffected>0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception occurred !",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
You can execute your query by ExecuteNonQuery() function
click a button to change the question in my Form and choices.. but this code only shows the last data of my table when i click it
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
im only starting in sql server
you should add some int type of data and you should check it from you sql statement then
you can get your willing data from database it something like this
don't forget to increment it in somewhere of you program and keep in mind of boundary of it
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question where id ="+one, conn);
public class Form1
{
private SqlConnection conn;
private SqlCommand command;
private SqlDataReader reader;
public Form1()
{
conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
command = new SqlCommand("SELECT * "+ "FROM question", conn);
try
{
conn.Open();
reader = command.ExecuteReader();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
else reader.Close();
}
}
this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
It gives the error connection was not closed. Connection's current state is open.
Please help out with the code.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string amount = dr.GetString(1);
textBox5.Text = amount;
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You should be using using blocks to help with managing your objects.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string cmdText = "Select * FROM [plan] where plantype=#planType";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#planType", comboBox1.Text);
var reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
string amount = reader.GetString(1);
textbox5.Text = amount;
}
}
}
Also note the use of parameterized queries to avoid SQL injection attacks. Since you are probably only expecting one value to be returned, you should specify the name of the column in the query and use ExecuteScalar instead of the reader and the while loop. The other alternative is to use CommandBehavior.SingleRow as the parameter to the command, which tells the command to just return a single row result.
You also have a cross-threading problem here, and you can solve it by using some invoking.
string amount = string.Empty;
if (reader.Read())
{
amount = reader.GetString(1);
}
if (this.InvokeRequired)
this.Invoke((MethodInvoker) delegate { textbox5.Text = amount; });
else
textbox5.Text = amount;
Another thing to note, is to give your controls meaningful names. Its a lot easier to debug or understand a control named cbx_PlanType than combobox1, or tbx_PlanAmount rather than textbox5.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string amount = dr.GetString(1);
textBox5.Text = amount;
}
// check if connection is open
if (con.State == 1)
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// check if connection is open
if (con.State == 1)
con.Close();
}
}
I have a c# login forum that has two text-boxes
1.username
2.password
I am trying to check if the user exists in my Oracle database or not. If so, I want it to do something (like call another forum, etc...), but I'm getting an error msg that says I have a missing expression. Whats wrong with it?
private void button1_Click(object sender, EventArgs e)
{
isUserExist(textBox1.Text,textBox2.Text);
}
public bool isUserExist(string username,string password)
{
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statementcmd = "SELECT * FROM register_user Where UserName=#username";
OracleConnection conn = new OracleConnection(connstring);
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = statementcmd;
cmd.Parameters.Add("#username", username);
if (conn.State != ConnectionState.Open)
{
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (!reader.HasRows)
{ MessageBox.Show("User Name Not Found"); }
if (!password.Equals(reader["password"].ToString()))
MessageBox.Show("Incorrect Password");
reader.Close();
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
You need to call the Read method on the DataReader before trying to access the properties.
if (reader.Read())
{
// Do stuff
}
Good luck!
1. you need to assign parameters before assigning commandstring to the CommandText.
2. you need to call Read() OracleDataReader object reader before accessing the records.
3. you should return true when true only when user is found.(in second if condition open curly braces is missing).
4. you can use using{} block for all IDisposable Implemented classes in your program so that their objects disposal will be taken care.(so you don't need to call Close() on Connection or Command objects)
Complete Solution:
public bool isUserExist(string username,string password)
{
bool status=false;
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statementcmd = "SELECT * FROM register_user Where [UserName]=#username";
using(OracleConnection conn = new OracleConnection(connstring))
{
using(OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.Parameters.Add("#username", username);//add parameters before assigning it to CommandText
cmd.CommandText = statementcmd;
if (conn.State != ConnectionState.Open)
{
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (!reader.Read())
{ MessageBox.Show("User Name Not Found"); }
if (!password.Equals(reader["password"].ToString()))
{
status=true;
MessageBox.Show("Incorrect Password");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
status=false;
}
return status;
}