When I add a Car in my application I get
The ConnectionString property has not been initialized.
I have the problem of ConnectionString property. I check similar question of mine but I found nothing helpfulness.
I use a class connection named dbConnection.cs:
class dbConnection
{
//Connection to database
private string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE".ToString();
public string Con
{
get
{
return con;
}
}
}
This is the code of my button
private void btnAddCar_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtCar = new DataTable();
BindingSource Car_bs = new BindingSource();
using (SqlCommand cmd = new SqlCommand("sp_Add_Car", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
//......
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtCar.Clear();
da.Fill(dtCar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
refreshCar();
}
This is the code of an another button working well without error
private void btnAddPayment_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtPayment = new DataTable();
using (SqlCommand cmd = new SqlCommand("sp_Add_Paiements", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id_paiement", SqlDbType.Char).Value = txtBoxPaymentId.Text;
cmd.Parameters.Add("#montant", SqlDbType.SmallMoney).Value = txtBoxAmount.Text;
cmd.Parameters.Add("#id_Location", SqlDbType.Char).Value = cmbpaymentLesaseId.Text;
//cmd.Parameters.Add("#status", SqlDbType.Char).Value = txtBoxStatusPayment.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtPayment.Clear();
da.Fill(dtPayment);
btnAddLease.Hide();
refreshPayments();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
btnAddPayment.Hide();
}
You aren't showing where you have initialized your dbConnection class. Changing it all to static will probably help, I'm guessing:
static class dbConnection
{
//Connection to database
private static string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE"
public static string Con
{
get
{
return con;
}
}
}
If your dbConnection class worked in one method but not the other, chances are you had it initialized in one and not the other. Unless you have to deal with different database connections, using a static class for your database connections is probably the best route.
Then you change your calling method like this:
using (SqlConnection con = new SqlConnection(dbConnection.Con))
{
// blah-blah
}
Assuming dc is your connection, then it has to be initialized with a connection string. Maybe - if it's a class - you have to set some properties, like database path, etc.
SqlConnection Con= New SQLConnection(#"Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE");
Related
I am having trouble with the following line:
MySqlDataReader DataReader = objDatabase.SetCommandType("GetRaceLevels").ExecuteReader();
It keeps returning the following error:
System.InvalidOperationException: 'Connection must be valid and open.'
private void RegisterForm_Load(object sender, EventArgs e)
{
HideMe();
MoveMe(-180);
MySqlConnection myConnection = objDatabase.GetConnection(); //must save the object based connection to a local variable for some reason.
myConnection.Open();
MySqlDataReader DataReader = objDatabase.SetCommandType("GetRaceLevels").ExecuteReader();
try
{
while (DataReader.Read())
{
cboRunnerTypes.Items.Add(DataReader[1]);
}
}
catch (Exception ex)
{
MessageBox.Show("Critical error!");
}
myConnection.Close();
}
I have tested the connection, it does work just fine, and it works during my login process.
The only other thing is this whole process utilises my clsDatabase class, that is where MySqlDataReader DataReader = objDatabase.SetCommandType("GetRaceLevels").ExecuteReader(); comes from.
This is the function on the clsDatabse class:
public MySqlCommand SetCommandType(string sProcedureName)
{
MySqlCommand myCommand = new MySqlCommand(sProcedureName, GetConnection()); //I think the problem is here, how am I fixing it though?
myCommand.CommandType = CommandType.StoredProcedure;
return myCommand;
}
I hope this all makes sense and I am not being extremely thick. Any help would be much appreciated! Thank you!
EDIT: The class:
class clsDatabase
{
private const string conString = "server = ; database = ; user = ; password = ; charset = utf8";
public MySqlConnection GetConnection()
{
MySqlConnection myConnection = new MySqlConnection(conString);
return myConnection;
}
public void EmailCommandCaller(MySqlCommand myCommand, string sEmail, string sContent)
{
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue(sEmail, sContent);
}
public void LoginCommandCaller(MySqlCommand myCommand, string sEmail, string sPassword, string sEmailContent, string sPasswordConetnt)
{
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue(sEmail, sEmailContent);
myCommand.Parameters.AddWithValue(sPassword, sPasswordConetnt);
}
public MySqlCommand SetCommandType(string sProcedureName)
{
MySqlCommand myCommand = new MySqlCommand(sProcedureName, GetConnection()); //I think the problem is here, how am I fixing it though?
myCommand.CommandType = CommandType.StoredProcedure;
return myCommand;
}
}
Everytime you call GetConnection() you're getting a brand new one. A new connection starts closed. Now, look at your SetCommandType method. It's instancianting a new MySqlCommand with a brand new connection, which is closed. You could open the connection in the method, but that is error prone, as you would end up with no means to close the connection afterward. Instead, instantiate the connection where you want to use it. Also, use using statements for better IDisposable handling.
private void RegisterForm_Load(object sender, EventArgs e)
{
HideMe();
MoveMe(-180);
using(MySqlConnection myConnection = new MySqlConnection(conString)){
myConnection.Open();
MySqlCommand myCommand = new MySqlCommand("GetRaceLevels", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
using(MySqlDataReader DataReader = myCommand.ExecuteReader()){
try
{
while (DataReader.Read())
{
cboRunnerTypes.Items.Add(DataReader[1]);
}
}
catch (Exception ex)
{
MessageBox.Show("Critical error!");
}
}
}
}
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
Trying to fill Combobox with data from a database and I'm using ExecuteReader as below, but when I try to instantiate my connection it shows me the error
Cannot implicitly convert type error
My DBConnect class code:
public class DBConnect
{
private SqlConnection connection;
private string servername = "10.1.76.109,1433";
private string database = "EngLib";
private string dbuser;
private string userpassword;
public DBConnect()
{
}
public void doDBConnect(string dbuserform, string userpasswordform)
{
dbuser = dbuserform;
userpassword = userpasswordform;
}
public void Initialize()
{
}
public bool openConnection()
{
string connectionString;
connectionString = "Server=" + servername + ";Database=" + database + ";user id=" + dbuser + ";Password=" + userpassword;
Console.WriteLine(connectionString);
connection = new SqlConnection(connectionString);
try
{
connection.Open();
return true;
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Não é possível contactar o servidor. Entre em contato com o administrador");
break;
case 18456:
MessageBox.Show("Usuário/Senha inválidos, tente novamente");
break;
}
return false;
}
}
My form code:
{
public Form2()
{
InitializeComponent();
}
public void Form2_Load(object sender, EventArgs e)
{
SqlDataReader rdr = null;
DBConnect sqlConnection;
sqlConnection = new DBConnect();
sqlConnection.doDBConnect(dbuserform: "usertest", userpasswordform: "usertest");
{
try
{
{
sqlConnection.openConnection();
SqlCommand sqlCmd;
sqlCmd = new SqlCommand("SELECT Material FROM EngLib");
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
comboBox1.Items.Add(sqlReader["Material"].ToString());
}
sqlReader.Close();
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
}
}
}
}
The user and password in the code is just temporary.
I think the problem is here:
DBConnect sqlConnection;
SqlCommand sqlCmd;
sqlCmd.Connection = sqlConnection;
SqlCommand expects that Connection is of type SqlConnection, but you are assigning your own class DBConnect.
Possible fixes:
Expose the connection property on DBConnect and use it.
Inherit DBConnect from SqlConnection.
Use SqlConnection directly.
An additional note: you are not disposing the SqlConnection inside your DBConnect class, which can lead to StackOverflowException. You should implement IDisposable.
namespace PCMS
{
public partial class frmPlayerInterface : Form
{
private OleDbConnection con = new OleDbConnection();
OleDbCommand com = new OleDbCommand();
private DataTable dt = new DataTable();
public frmPlayerInterface(string getUser)
{
InitializeComponent();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\SDP\PCMS\SDP.accdb";
lblUser.Text = getUser;
}
private void btnEnquire_Click(object sender, EventArgs e)
{
frmEnquire frmenq = new frmEnquire();
frmenq.ShowDialog();
}
private void btnTopUp1_Click(object sender, EventArgs e)
{
frmTopUp frmTU = new frmTopUp();
frmTU.ShowDialog();
}
private void frmPlayerInterface_Load(object sender, EventArgs e)
{
con.Open();
OleDbCommand comm = new OleDbCommand();
String sql = "select Balance from PlayerAccount where Player_User=#user";
comm.Parameters.Add(new OleDbParameter("user", lblUser.Text));
comm.CommandText = sql;
OleDbDataReader cursor = comm.ExecuteReader();
while (cursor.Read())
{
lblBalance.Text = cursor["Balance"].ToString();
}
con.Close();
}
}
}
Hey sorry guys asking this again but ive been trying this for the past three hours and wave the white flag. Still getting the same error.
I just want to have the selected balance value from the database to be shown in the label.
Thanks ><
You're not associating the connection with the command object:
con.Open();
String sql = "select Balance from PlayerAccount where Player_User=#user";
OleDbCommand comm = new OleDbCommand(sql, con);
Note that reusing a connection is not always the best design. Connections are pooled in .NET, so recreating them is generally not an expensive operation. A better design would be to store the connection string as a class property then just create a connection when you need it:
private string ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\SDP\PCMS\SDP.accdb";
// or better yet - pull form app.config...
and when you use it:
String sql = "select Balance from PlayerAccount where Player_User=#user";
using(OleDbConnection con = new OleDbConnection(ConnectionString))
{
con.Open();
using(OleDbCommand comm = new OleDbCommand(sql, con))
{
... Add parameters, execute query, return results
}
}
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";
}