As said in the title, I tried to write some prepared statement on Visual Studio 2017.
But when Starting my program, I have an exception, called
System.InvalidOperationException :'The connection property has not
been set.'
Here's the associated code :
namespace Sequence
{
class Database
{
private MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlConnection conn; //new connection
public void Connect()
{
string myConnectionString; //connection String
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=internship;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
public void Disconnect()
{
try
{
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
public void AddData()
{
cmd = new MySql.Data.MySqlClient.MySqlCommand();
//Connecting to database
Connect();
try
{
//Prepare a statement
cmd.CommandText = "INSERT INTO storing VALUES(#longitude, #latitude, #status, #path)";
cmd.Prepare();
//Adding values
cmd.Parameters.AddWithValue("#longitude", 0.5);
cmd.Parameters.AddWithValue("#latitude", 0.5);
cmd.Parameters.AddWithValue("#status", "false");
cmd.Parameters.AddWithValue("#path", "C:\\temp\\sequence");
//Executes the Query
cmd.ExecuteNonQuery();
//Writes in Console
Console.WriteLine("Line added successfully");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occured: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
This is my class that connects to the database.
I have a main program where I just wrote this :
static class Program
{
[STAThread]
static void Main()
{
Database db = new Database();
db.Connect();
db.AddData();
db.Disconnect();
}
}
Any idea of why I get this exception ?
I followed the tutorial on this link :
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html
Thanks in advance
You didn't set the connection property of your command:
cmd.Connection = conn;
Although it's recommended to use the using-statement that Provides a convenient syntax that ensures the correct use of IDisposable objects like SqlConnection. It will also close the connection
Related
Goal:
My goal is to create a MySQL query using C#, and on successful query I'd like to use File.Copy... and vice versa.
This is my current code:
//Try run code
try
{
//Add record to MySQL
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
using (var cmd = new MySqlCommand("INSERT INTO files (document_name, path, version, section, user_modified, date_modified)" +
" values (#doc, #path, #version, #section, #user, NOW());", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#doc", docName.Text);
cmd.Parameters.AddWithValue("#path", $"{finalPath}Section {Section.Text}\\{docName.Text}{Path.GetExtension(fileName)}");
cmd.Parameters.AddWithValue("#version", versionNumber.Text);
cmd.Parameters.AddWithValue("#section", Section.Text);
cmd.Parameters.AddWithValue("#user", UserDetails.userId);
cmd.ExecuteNonQuery();
}
}
//Copy file into new directory
File.Copy(fileName, $"{finalPath}Section {Section.Text}\\{docName.Text}{Path.GetExtension(fileName)}");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
Question:
What is a good method to achieve the following..
If MySQL query not successful then do not do anything and stop and return to where the error was.
If MySQL query was successful and File.Copy wasn't (Ran into an error for any reason) - then recover the query, delete whatever was inserted and go back all the way to step one.
How can this be achieved?
Edit 10/06/2020
I have managed to get the following code :
//Try run MySQL query with roll back function if failed.
public void RunTransaction(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(ConnectionString.ConnString);
myConnection.Open();
MySqlCommand myCommand = myConnection.CreateCommand();
MySqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "INSERT INTO files (document_name, path, version, section, user_modified, date_modified, review_date)" +
" values (#doc, #path, #version, #section, #user, NOW(), NOW() + interval 12 month);";
myCommand.Parameters.AddWithValue("#doc", docName.Text);
myCommand.Parameters.AddWithValue("#path", $"{finalPath}Section {Section.Text}\\{docName.Text}{Path.GetExtension(fileName)}");
myCommand.Parameters.AddWithValue("#version", versionNumber.Text);
myCommand.Parameters.AddWithValue("#section", Section.Text);
myCommand.Parameters.AddWithValue("#user", UserDetails.userId);
myCommand.ExecuteNonQuery();
myTrans.Commit();
}
catch (Exception e)
{
try
{
myTrans.Rollback();
}
catch (MySqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}
Question..
How would I then implement the File.Copy function to suit my goal?
I have this source.. https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo.copyto?view=netcore-3.1
but not sure where to code in my current code?
Im trying to pass two parameters to my oracle package.
I can get the parameters, but it is not being passed into the database. Every time I run the application it fails to make a connection and goes straight to my try catch method.
Is there something I am doing wrong?
This is what I have so far:
using System.Data.OracleClient;
private void btnGetData_Click(object sender, EventArgs e)
{
GetOrders_OracleCon_GetData(Parameter1,Parameter2);
// when i output or add in a break i can see that the data does come into the Parameter values. However after that it doesnt go to my db
}
public void GetOrders_OracleCon_GetData(Int32 PM1, String PM2)
{
using (OracleConnection objConn = new OracleConnection("Data Source=" + dbcon + "; User ID=" + uid + "; Password=" + pass))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "PCK_Orders.get_data";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("pm1", OracleType.Number).Value = PM1;
objCmd.Parameters.Add("pm2", OracleType.VarChar).Value =PM2;
objCmd.Parameters.Add("selected_orders", OracleType.Cursor).Direction = ParameterDirection.Output;
try
{
objConn.Open();
OracleDataReader objReader = objCmd.ExecuteReader();
if (objReader.HasRows)
{
GetOrders_GetData(objReader);
btnCancel.Enabled = true;
}
else
{
Timer_ProgBar.Stop();
MessageBox.Show("Orders for this Datedoes not exist", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
GP_ClearAllFields("Y", "Y");
Timer_ProgBar_Initialize(0, "");
}
}
catch (Exception)
{
Timer_ProgBar.Stop();
MessageBox.Show("An error has occured");
// this is the error that i catch but im not sure what is causing it. am i missing something?
Timer_ProgBar_Initialize(0, "");
}
objConn.Close();
}
}
I want to make parallel database saving in my system. I have two destination that the database will be saved. First in the local computer (so I'm using localhost instead of the IPaddress) and the remote PC (i'm using the IP address to access it).
Here is my code :
static string MyConnectionString = "Server=localhost;Port=3306;Database=database freq logger;Uid=root;";
static string MyConnectionString2 = "Server=192.168.41.105;Port=3306;Database=database freq logger;Uid=irfan;";
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlConnection connection2 = new MySqlConnection(MyConnectionString2);
MySqlCommand cmd;
public void Read()
{
while (port.IsOpen)
{
try
{
if (port.BytesToRead > 0)
{
string message = port.ReadLine();
this.SetText(message);
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO frequency(value)VALUES(#message)";
cmd.Parameters.AddWithValue("#message", message);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
connection.Close();
if (connection2 != null && connection2.State == ConnectionState.Closed)
{
connection2.Open();
try
{
cmd = connection2.CreateCommand();
cmd.CommandText = "INSERT INTO frequency(value)VALUES(#message)";
cmd.Parameters.AddWithValue("#message", message);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
connection2.Close();
}
}
}
catch (TimeoutException) { }
}
}
So I have 2 connectionsql (connection1 and connection2).
And I want to ignore the connection2 althought the connection is not connect. The connection is ethernet LAN. So when I unplug the LAN, I hope my program still running.
I always get the error (when I suddenly unplug the ethernet when the program running) in the "connection2.Open();".
I need your help, thank you
Don't try to monitor the connection pro-actively, just trap the resulting Exception and ignore it. Your problem is that your Connection2.Open() is not within the Try{} Catch{} block but outside it.
Try this
try
{
connection2.Open();
cmd = connection2.CreateCommand();
cmd.CommandText = "INSERT INTO frequency(value)VALUES(#message)";
cmd.Parameters.AddWithValue("#message", message);
cmd.ExecuteNonQuery();
connection2.Close();
}
catch
{
// Do nothing - this should continue to work without being able to make the connection
}
I developed a POS like application and during testing with 2 PCs I didn't encounter any problems with the speed. It's just a simple LAN cable setup between 2 computers. But when I deployed it in a client, it ran slow.
The client has 1 PC serving as the admin and the main server, and there are 2 more PCs serving as the cashier. All connected in a router. The cashiers are connected to the admin's PC (main server) to retrieve, insert, update and delete data. I just want to ask if there are processes that needs to be done in MySQL or are there anything wrong with my codes when connecting to the database.
Here's my sample code for connecting to the database, I doubt having problems with it as this has been the standard in connecting to a database and adding records. Just in case I might bore you with codes, you can simply jump to the second code I posted, I have a comment there asking if the initialization of my class is correct. Thanks everyone!
class DBConnection
{
private MySqlConnection connection;
private MySqlCommand cmd;
private MySqlDataReader dr;
private DataTable tbl;
private MySqlDataAdapter da;
private DataSet ds;
private string connectionString;
private string server;
private string database;
private string uid;
private string password;
private frmNotifOk myNotification;
public DBConnection()
{
Initialize();
}
private void Initialize()
{
server = "CASHIER";
database = "sampledb";
uid = "root";
password = "samplepassword";
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
}
return false;
}
}
private void CloseConnection()
{
try
{
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
public void AddRecord(String DBQuery, bool showNotif)
{
string query = DBQuery;
bool notify = showNotif;
try
{
if (this.OpenConnection() == true)
{
cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
if (notify)
{
MessageBox.Show("Item successfully added.");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
this.CloseConnection();
}
}
And finally, here's how I use the method in a form:
public partial class frmNewCashier : Form
{
private DBConnection dbConnect;
string sampleDataSource= "SELECT * FROM SampleTable";
public frmNewCashier()
{
InitializeComponent();
//Is this the correct place of initializing my DBConnection class?
dbConnect = new DBConnection();
}
private void frmCashier_Load(object sender, EventArgs e)
{
try
{
dgvSearchItems.DataSource = dbConnect.DatabaseToDatagrid(dgvSearchItemsDataSource);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
I put the initialization of DBConnection class in public frmNewCashier(), is this the correct place or should I put it in Load event or somewhere? I'm thinking if this has bearing to the slowness of database. Aside from this question, do you know anything that I might have missed that causes the slowness?
class DBConnect
{
public MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
server = "localhost";
database = "db_sea_horses";
uid = "root";
password = " " ;
//password = "123";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
public bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{ //0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
public bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
class DBmethods : DBConnect
{
DataSet dataset2;
public void input_sql(string query)
{
try
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
int x = cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
catch(MySqlException myex)
{
MessageBox.Show(ex.Message);
}
}
///////////////////////////////////////////////
///// select
/////////////////////////////////////////////
public DataSet output_sql(string query,String table_name)
{
//Open connection
this.OpenConnection();
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, connection);
adapter.Fill(dataset, table_name);
//close Connection
this.CloseConnection();
//return list to be displayed
return dataset;
}
}
}
method calling example
1) insert / update / delete statement
DBmethods dbm = new DBmethods();
dbm.input_sql(" you can excute insert / update / delete query");
2) select statement
DataSet ds = dbm.output_sql("select * from storage_bunkers where job_id LIKE '%" + itemname.Text + "%' ", "storage_bunkers");
DataView myView = ((DataTable)ds.Tables["storage_bunkers"]).DefaultView;
dataGridView1.DataSource = myView;
First, try pinging from client machine to server which has installed SQL server. If it is taking too much time then there's problem with network connection.
If not, put a debug point and try debugging then identify the location that taking too long. Then you will able to get a answer.
Also, do not forget to close each and every db connection after using that.
I have a problem running a simple insert query from my C# app towards a Postrges DB.
This is the function that builds the query:
string push = "INSERT INTO \"Tasks\"( \"TName\", \"Desc\", \"TType\", \"DCreated\", \"DEnd\") VALUES (\'" + this.Name + "\',\'" + this.Descr + "\'," + this.Type + ",\'" + this.StartDate + "\', \'" + this.EndDate + "\');";
GenericDbClass.ExecutePush(push);
And this is the string that gets passed to the DB:
INSERT INTO "Tasks"( "TName", "Desc", "TType", "DCreated", "DEnd") VALUES ('dddddd','dddddddddddd',3,'13.04.2015 17:00', '24.04.2015 16:42');
If I copy the string and run it inside pgAdmin it works right of the bat, but from here it doesn't do anything - no exceptions thrown,no errors, nothing in the logs, as if it just doesn't reach the server.
In addition here is the push method:
public static void ExecutePush(string sql)
{
try
{
NpgsqlConnection conn = new NpgsqlConnection(GenericDbClass.GetDbConnString());
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
conn.Close();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
Edit: This is the working solution I found
public static void ExecutePush(string sql)
{
try
{
NpgsqlConnection conn = new NpgsqlConnection(GenericDbClass.GetDbConnString());
conn.Open();
NpgsqlCommand nc = new NpgsqlCommand(sql, conn);
nc.ExecuteNonQuery();
conn.Close();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
Means "Please create a data-adaptor that uses the INSERT SQL passed as sql to do a selection". That doesn't make much sense, and then you don't do anything with it, anyway.
conn.CreateCommand(sql).ExecuteNonQuery();
Seems more like what you want.