I have the following code behind a button in Visual Studio 2010
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection Con = new SqlCeConnection();
Con.ConnectionString = "Data Source = 'DB.sdf';" + "Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin");
try
{
Con.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCeDataReader Reader=Query.ExecuteReader();
MessageBox.Show(Reader["Password"].ToString());
}
It works fine execute and no exception in connection but when I press the button it raises an exception saying
Error: Execute Reader Connection Property Has Not Been Initialized
I'm not going to attempt to comment on database access code in a UI event handler, it will detract from the answer too much. All I will say is, try not to do it.
You haven't associated the connection with the command, either in the command constructor or the relevant Connection property.
I would re-write the entire method to the following to cut out the dangerous try-catch (catching everything, very bad practice) and to utilise the fact using statements also handle object disposal for you:
string password = null;
using (var conn = new SqlCeConnection("Data Source = 'AlviMBRental.sdf'; Password='my Password';"))
using (var comm = new SqlCeCommand("SELECT Password FROM Admin", conn))
{
conn.Open();
using (var reader = comm.ExecuteReader())
{
password = (string)reader["Password"];
} // Dispose reader
// Alternatively, if the resultset is single column and single row, you can do:
var passwordScalar = (string)comm.ExecuteScalar();
} // Dispose command, close / dispose connection.
MessageBox.Show(password ?? "No password found.");
You are not associating your command with your connection - try this:
SqlCeConnection Con = new SqlCeConnection("Data Source = 'AlviMBRental.sdf';Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin", Con); // <== specify "Con" here!
Otherwise, your SqlCeCommand has no connection to work with....
Try like this:
private void button1_Click(object sender, EventArgs e)
{
var connectionString = "Data Source='AlviMBRental.sdf';Password='my Password';";
using (var con = new SqlCeConnection(connectionString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT Password FROM Admin";
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show(reader["Password"].ToString())
}
}
}
}
Make sure you have associated the connection with the command object. Also make sure you have wrapped IDisposable objects in using statements as shown in my example.
Related
I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
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();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET
I'm coding a Windows Forms login page for an administration application. My problem is, that when I try to log on, I get the error message
System.InvalidOperationException: 'The connection is already open.'
Any help would be appreciated
public partial class Form1 : Form
{
MySqlConnection con = new MySqlConnection (#"Database= app2000; Data Source = localhost; User = root; Password =''");
int i;
public Form1()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnLogin_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM adminlogin WHERE username='" + txtBoxUsername + "'AND password='" + txtBoxPassword + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
lblerrorInput.Show();
}
else
{
this.Hide();
Main ss = new Main();
ss.Show();
}
}
}
Do not cache Connection, it's a typical antipattern, but recreate it when you need it
public partial class Form1 : Form {
...
//DONE: Extract method
private static bool UserExists(string userName, string password) {
//DONE: Do not cache connections, but recreate them
using (MySqlConnection con = new MySqlConnection (#"...") {
con.Open();
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = con.CreateCommand()) {
cmd.CommandType = CommandType.Text;
//DONE: Make query being readable
//DONE: Make query being parametrized
cmd.CommandText =
#"SELECT *
FROM adminlogin
WHERE username = #UserName
AND password = #PassWord"; // <- A-A-A! Password as a plain text!
//TODO: the simplest, but not the best solution:
// better to create parameters explicitly
// cmd.Parameters.Add(...)
cmd.Parameters.AddWithValue("#UserName", txtBoxUsername);
cmd.Parameters.AddWithValue("#PassWord", txtBoxPassword);
// If we have at least one record, the user exists
using (var reader = cmd.ExecuteReader()) {
return (reader.Read());
}
}
}
}
Finally
private void btnLogin_Click(object sender, EventArgs e) {
if (!UserExists(txtBoxUsername.Text, txtBoxPassword.Text))
lblerrorInput.Show();
else {
Hide();
Main ss = new Main();
ss.Show();
}
}
You forgot to close the connection, use con.Close() at the end to close the connection and avoid this error the next time the event fires.
There are some mistakes in your code.
You should close the sql connection when you finished your process.
I suggest you to use using statement to dispose connection instance after complete database actions.
Also, you should use command parameters to prevent Sql injection.
You can declare connection string like this;
private string _connectionString = #"Database= app2000; Data Source = localhost; User = root; Password =''";
The method part looks like;
using (var con = new MySqlConnection(_connectionString))
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM adminlogin WHERE username = #username and password = #password";
cmd.Parameters.AddWithValue("#username", txtBoxUsername);
cmd.Parameters.AddWithValue("#password", txtBoxPassword);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
lblerrorInput.Show();
}
else
{
this.Hide();
Main ss = new Main();
ss.Show();
}
con.Close();
}
First, don't cache your Connection objects. It's a terrible practice and I've had to go back and fix it every time I accept a new job and inherit code. Most database access classes implement IDisposable, so use using and take advantage of it to keep your code clean. FYI, Readers and Adapters are also IDisposable so you can do the same with them, too.
string command = "select stuff from mydata";
string connection = GetConnectionStringFromEncryptedConfigFile();
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(command, conn))
{
cmd.Connection.Open();
//do stuff
}
}
Second, if you're forced to use a cached connection (i.e., you inherited horrible code and don't have time to fix it yet), check your State first.
if(conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
Note that there are a lot more states than just Open and Closed, and if you try to open a connection that is busy, you'll still get errors. It's still a much wiser approach to use the IDisposable implementations with using so you don't have to worry about this sort of thing so much.
Please I want to know how to retrieve a data on the same row in a MS Access database using Visual C#
I want to get the meaning of a keyword from my database when it is selected from a combo box
Here is my code;
private void cmd_SearchResult_Click(object sender, EventArgs e)
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\hp\Documents\KnowledgeBase.accdb;
Persist Security Info=False;";
using (var conn = new OleDbConnection(connection.ConnectionString))
using (var command = connection.CreateCommand())
{
command.Connection = conn;
command.CommandText = "select Meaning from KnowledgeBase where Keyword = #Keyword";
command.Parameters.AddWithValue("Keyword", String.Copy(cbo_SearchResult.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
lbl_Display.Text = reader["Meaning"].ToString();
}
}
}
Try something more like the following. I'm not sure what the "connection" object is but lets go with a simple string as shown.
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\hp\Documents\KnowledgeBase.accdb;
Persist Security Info=False;";
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "select Meaning from KnowledgeBase where Keyword = #Keyword";
command.Parameters.AddWithValue("Keyword", cbo_SearchResult.Text);
object result = command.ExecuteScalar();
if (result != null)
{
lbl_Display.Text = result.ToString();
}
}
}
When I enter a RegiD to check-in, it takes me to my form 2 but it happens even if the number is not in my RegiD column in my SQL Database. How do it get it to check if the number I entered in my text box is in my SQL Database?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-UHGLPQ8\SQLEXPRESS;Initial Catalog=Test Vol;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM MastVolData WHERE [RegiD] =' " + textBox1.Text + "'" , con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read() == true)
{
using (Form2 frm = new Form2(textBox1.Text))
{
frm.ShowDialog();
}
}
else
{
MessageBox.Show("Wrong I.D! Please try again!");
}
textBox1.Clear();
}
}
}
First, you need to stop concatenating strings to create SQL statements and start using parameterized queries. Otherwise you are risking SQL Injection attacks.
Second, you need to learn when to use the using statement.
Third, You need to learn about the HasRows property of the SqlDataReader.
Your code should end up looking like this:
private void button1_Click(object sender, EventArgs e)
{
// use this local variable to prevent keeping sql connection and an active data reader longer than neccessary
var hasRows = false;
// You should really get the connection string from your web.config file, I left it hard coded so that you can test.
var connectionString = #"Data Source=DESKTOP-UHGLPQ8\SQLEXPRESS;Initial Catalog=Test Vol;Integrated Security=True";
// Use the using statement for any local variable that implements the IDisposable interface
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("SELECT * FROM MastVolData WHERE [RegiD] = #RegiD;", con))
{
cmd.Parameters.Add("#RegiD", SqlDbType.VarChar).Value = textBox1.Text;
con.Open();
using (var dr = cmd.ExecuteReader())
{
hasRows = dr.HasRows;
}
}
}
// Now that your sql connection is closed and disposed, you can use ShowDialog
if (hasRows)
{
using (Form2 frm = new Form2(textBox1.Text))
{
frm.ShowDialog();
}
}
else
{
MessageBox.Show("Wrong I.D! Please try again!");
}
textBox1.Clear();
}
}
this code is successfully inserting a new value in a SQL db, but only when I insert constant values.
I need help where it says **(?)** in the code below, where I want to insert new values without specifying constants in the code.
What I mean is, I want to be able to type any random value in output window and it gets inserted into the SQL db.
private void InsertInfo()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
connetionString = #"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connetionString);
string sql = "insert into record (name,marks) **values( ?))";**
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
There is no need to use an adapter here; that is not helping you. Just:
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into record (name, marks) values (#name, #marks)";
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("marks", marks);
conn.Open();
cmd.ExecuteNonQuery();
}
or with a tool like "dapper":
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString)) {
conn.Open();
conn.Execute("insert into record (name, marks) values (#name, #marks)",
new {name, marks});
}
Those '?' are termed as parameters. From what I understand, you are wanting to use a parametrized query for your insert which is a good approach as they save you from chance of a SQL injection. The '?' sing in your query is used when you are using an
OLEDBConnection & Command object.
Normally, you would use '#' symbol to specify a parameter in your query. There is no need for an adapter. You just
//Bind parameters
// Open your Connection
// Execute your query
// Close connection
// return result
Parametrized queries 4 Guys from Rolla
MSDN: How to Protect from SQL injection in ASP.NET