oledb connection string not initialized - c#

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
}
}

Related

Creating a Data Reader from a C# Object

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!");
}
}
}
}

c# System.InvalidOperationException: 'The connection is already open.'

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.

Display DateTime iin C# and WPF

I have a DateTime variable selected in a 1st window and I'm trying to display in in a 2nd window. It connects to the DB as it should be,but it appears a random data from the DB,not the selected one.
Here is the code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Are you sure?");
Window1 win1 = new Window1();
win1.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
{
string connectionString = null;
SqlConnection cnn;
connectionString =
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True";
try
{
SqlConnection con =
new SqlConnection(
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"insert into [Event] (Description,StartData,EndData,Type) values (#description,#startdata,#endata,#type)";
cmd.Parameters.AddWithValue("description", descriptionTxt.Text);
cmd.Parameters.AddWithValue("startData", StartDate.Value);
cmd.Parameters.AddWithValue("endata", EndDate.Value);
cmd.Parameters.AddWithValue("type", typeTxt.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
////Window2 win = new Window2(id);
//Window2 win3 = new Window2();
//this.Close();
//win3.Show();
SqlConnection conn =
new SqlConnection(
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
int query= Convert.ToInt32(comm.CommandText = "select MAX(StartData) from [Events]");
Window2 win = new Window2(query);
win.Show();
}
The error is input string was not in a correct format. How can I convert it?
There are a few things you need to look at/consider in your code, first is your issue.
This line of code:
int query= Convert.ToDateTime(comm.CommandText = "select MAX(DateTime) from [Events]");
Won't achieve what you are after as you aren't executing the code. You are actually trying to convert your command object to a Date Time.
Earlier in your method you are writing to the database and part of that you call the following:
cmd.ExecuteNonQuery();
There are various other methods that you have on the command object that all work in different ways. To read about them visit this MSDN page, but essentially you probably want to use the ExectuteScalar method for what you are trying to do.
Next, I would consider moving your connection string to the app.config file and accessing it from there rather than typing it out multiple times.
And finally, I would use a using statement for each of your Connection's so that you ensure they are being disposed of correctly.
Just some extra food for thought.

Load two / several MS Access Table into C# Windows Form

I´m asking how to connect two or more tables from an MS Access table into c# Windows forms?.
I get the error, that ue cant find the second table:
public partial class Form1 : Form
{
private OleDbConnection connection = new OleDbConnection();
private OleDbConnection connection2 = new OleDbConnection();
public Form1()
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\MitarbeiterDaten2.accdb;
Persist Security Info=False;";
connection2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\DatenbankAbteilung.accdb;
Persist Security Info=False;";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader["ABTEILUNG"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
}
Anybody got an solution?
Its just about, how to connect two or more MS Access tables into C# Windows forms.
You can reuse the the objects, and can get data from various tables or databases, as :
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader("ABTEILUNG").ToString());
}
reader.Close(); //' Always Close ther Reader. Don't left it open
connection2.Open();
command.Connection = connection2; //' Reusing Same Command Over New Connection
command.CommandText = "Select Field2 from Table2";
while (reader.Read)
{
if (!(Convert.IsDBNull(reader("Field2")))) //' Checking If Null Value is there
{
Abteilung.Items.Add(reader("Field2").ToString());
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
connection2.Close();
}
}
How about using using blocks to take care of the commands and connections and then using DataAdapter to get the job done easily. I use some code like this.
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(MDBConnection.ConnectionString))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT Column FROM Table1", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT AnotherColumn FROM Table2", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;

Deleting records from the created form in c#

I m working with c#, in this i want to delete record from the form for that i have the following code..
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
con.Open();
string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";
}
but i m not getting the answer...
You need to setup an OleDbCommand
The full code for your case,
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";
con.Open();
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
}
For more information of the whole implementation, read here
http://www.java2s.com/Code/CSharp/Database-ADO.net/DeletedatabaserecordsthroughOleDbCommandandverifytheresults.htm
You need to execute an OleCommand with your SQL and connection.

Categories

Resources