How to call a method from one class to another class - c#

hellow im new to this forum. i searched for a day now and i cant find anything to solve my problem
i need to call a function in a class from a form class.
but evrytime i try i get error 'cs0117' 'DBconnection does not contain a definition for insert' 'line 19'
this is my form where i want to call an class with the line 'DBconnection.insert();
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class FrmEditUser : Form
{
public FrmEditUser()
{
InitializeComponent();
DBconnection.insert();
}
private void LblUserName_Click(object sender, EventArgs e)
{
}
}
}
this is the class where i wanna get the funcion from
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
//using System.Data.Odbc; //added libary
namespace WindowsFormsApplication2
{
public class DBconnection : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public void DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "tablemembers";
uid = "******";
password = "******";
string connectionString;
connectionString = "localhost=" + server + ";" + "tablemembers=" + database + ";" + "******=" + uid + ";" + "******=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
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
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//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
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
string query = "UPDATE tableinfo SET name='Joe', age='22' WHERE name='John Smith'";
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Delete statement
public void Delete()
{
string query = "DELETE FROM tableinfo WHERE name='John Smith'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM tableinfo";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["name"] + "");
list[2].Add(dataReader["age"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
public int Count()
{
string query = "SELECT Count(*) FROM tableinfo";
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar() + "");
//close Connection
this.CloseConnection();
return Count;
}
else
{
return Count;
}
}
//Backup
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(#"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup!");
}
}
//Restore
public void Restore()
{
try
{
//Read file from C:\
string path;
path = "C:\\MySqlBackup.sql";
StreamReader file = new StreamReader(path);
string input = file.ReadToEnd();
file.Close();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysql";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = string.Format(#"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to Restore!");
}
}
}
}
thanks in advance

Initialize your DBconnection class inside FrmEditUser constructor, because insert() method is not a static method so you can not access it without instantiation
public FrmEditUser()
{
InitializeComponent();
DBconnection connect = new DBconnection();
connect.insert();
}

Related

How do i add textbox values to Access database?

I want to add textbox values to relevant columns in access database, the connection has been established but when i click the submit button the values are not added.
here is the code i tried, any help is appreciated
protected void Button1_Click(object sender, EventArgs e)
{
string EmailAddress = TextBox1.Text;
string UserName = TextBox2.Text;
string Password = TextBox3.Text;
try
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");
OleDbCommand cmd = new OleDbCommand();
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)");
con.Open();
if (con.State == ConnectionState.Open)
{
TextBox1.Text = "sssss";
cmd.Parameters.Add("#EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox3.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception error)
{
//Show error message as error.Message
}
}
Try adding connection string with OleDbCommand.
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)",con);
Here is an example were all data operations reside in a class. If the add new record is successful the new primary key is returned. On failure you can query the exception that raised the problem for failure.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace MS_AccessAddNewRecord_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addRecordButton_Click(object sender, EventArgs e)
{
var ops = new Operations();
var newId = 0;
if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
{
newIdentifierTextBox.Text = $"{newId}";
}
else
{
MessageBox.Show($"{ops.Exception.Message}");
}
}
}
/// <summary>
/// This class should be in a separate class file, I placed it here for easy of learning
/// </summary>
public class Operations
{
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.ACE.OLEDB.12.0",
DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
};
private Exception mExceptiom;
public Exception Exception
{
get
{
return mExceptiom;
}
}
/// <summary>
/// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
/// </summary>
/// <param name="pName"></param>
/// <param name="pContactName"></param>
/// <param name="pContactTitle"></param>
/// <param name="pIdentfier"></param>
/// <returns></returns>
public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
{
bool Success = true;
try
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " +
"Values(#CompanyName,#ContactName, #ContactTitle)";
cmd.Parameters.AddWithValue("#CompanyName", pName);
cmd.Parameters.AddWithValue("#ContactName", pContactName);
cmd.Parameters.AddWithValue("#ContactTitle", pContactTitle);
cn.Open();
int Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
cmd.CommandText = "Select ##Identity";
pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
catch (Exception ex)
{
Success = false;
mExceptiom = ex;
}
return Success;
}
}
}
Perhaps in the Page_Load method you do not have a if(!isPostback) and so the value of the TextBoxes are getting reset on a postback before the Button1_Click method is executed.
If EmptyWaterHole's answer is not the problem, is it erroring out on the connection?
Be sure 'VarChar' is the correct data type for each of the fields.
Also, be sure the values do not exceed the size (ie: if you set the field to only allow up to 25 characters and your value is over 25 characters, the value will not be added).
In addition, if you are not allowing nulls and one of the values exceeds the limit, the whole record will not be added.
Mr. Hungry. Try it like this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
try this it will work if you are using access as your database
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(#patientName,#tel,#hostel,#id no,#department,#diagnose,#gender)";
connection.Open();
command.Parameters.AddWithValue("#patientName", textBox1.Text);
command.Parameters.AddWithValue("#tel", textBox2.Text);
command.Parameters.AddWithValue("#hostel", textBox3.Text);
command.Parameters.AddWithValue("#id no", textBox4.Text);
command.Parameters.AddWithValue("#department", textBox5.Text);
command.Parameters.AddWithValue("#diagnose", richTextBox1.Text);
command.Parameters.AddWithValue("#gender", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Patient record Have been save successfully....");
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}

Receiving an error when insert data into a .dbf file

Backgournd
I am currently working on a project which will need me to create a local .dbf file which I must then populate with a value. I am currently able to create a .dbf file in a test dir and adding a column to it, however when I later try to add a value to the column, it errors out.
Problem
I am currently not able to write to the column Public in the .dbf file which I created. When the code goes into ExecuteNonQuery();, it an error and is caught in my catch statement.
Working code
public static bool CreateDBF()
{
try
{
string dbfDirectory = #"c:\Users\me\Desktop\New911";
string connectionString = "Provider=VFPOLEDB;Data Source=" + dbfDirectory;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "create table CustomProperties(Public C(60))";
command.ExecuteNonQuery();
connection.Close();
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
}
return true;
}
catch (Exception ex)
{
throw;
}
}
Working Code - appendix:
The above block of code successfully create the .dbf file with the column which I want as the following image will show
Not working code:
public static bool InsertDataIntoDBF(string path)
{
try
{
string strLogConnectionString = "Provider=VFPOLEDB;Data Source=" + path + ";Collating Sequence=machine;Mode=ReadWrite;";
string query = #"INSERT INTO CustomProperties (Public)";
using (OleDbConnection connection = new OleDbConnection(strLogConnectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
new OleDbCommand("set null off", connection).ExecuteNonQuery();
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
catch (Exception ex)
{
throw;
}
}
Updated code blocks
Working block:
public static bool CreateDBF()
{
try
{
string dbfDirectory = #"c:\Users\er4505\Desktop\New911";
string connectionString = "Provider=VFPOLEDB;Data Source=" + dbfDirectory;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "create table CustomProperties(Public C(60))";
command.ExecuteNonQuery();
connection.Close();
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
return true;
}
catch (Exception ex)
{
string viewError = JsonConvert.SerializeObject(ex);
return false; << I have a breakpoint here
}
}
Non-working block:
public static bool InsertDataIntoDBF(string path)
{
try
{
string strLogConnectionString = "Provider=VFPOLEDB;Data Source=" + path + ";Collating Sequence=machine;Mode=ReadWrite;";
string query = #"INSERT INTO CustomProperties (Public) VALUES (#Public)";
using (OleDbConnection connection = new OleDbConnection(strLogConnectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
catch (Exception ex)
{
string viewError = JsonConvert.SerializeObject(ex);
return false; << breakpoint here
}
}
Error caught:
oledbErrors
Message: Syntax error.
NativeError: 0
Source: Microsoft OLE DB Provider for Visual FoxPro
ClassName: System.Data.OleDb.OleDbException
Message: Syntax error.
This works for me. Try it
static void Main(string[] args)
{
try
{
CreateDBF();
Console.WriteLine(ReadDB());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static string dbfDirectory = #"c:\Test\dbTest";
private static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbfDirectory + ";Extended Properties = dBase IV";
public static bool CreateDBF()
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "Create Table CustomProperties ([Public] char(50))";
command.ExecuteNonQuery();
connection.Close();
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
return true;
}
public static bool InsertDataIntoDBF(string path)
{
string query = #"INSERT INTO CustomProperties ([Public]) VALUES (#Public)";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
public static string ReadDB()
{
string res = string.Empty;
string query = #"SELECT * FROM CustomProperties";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
res = (string)command.ExecuteScalar();
connection.Close();
}
return res;
}
The error was purely syntax, and I was guided by a really good example which I found in the following link
https://social.msdn.microsoft.com/Forums/en-US/24eac4c5-3a4d-43f4-8607-ef684919c4af/command-contains-unrecognized-phrasekeyword-vbnet?forum=visualfoxprogeneral
Working Code Blocks
public static bool CreateDBF()
{
try
{
string dbfDirectory = #"c:\Users\er4505\Desktop\New911";
string connectionString = "Provider=VFPOLEDB;Data Source=" + dbfDirectory;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "create table CustomProperties(Public C(60))";
command.ExecuteNonQuery();
connection.Close();
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
return true;
}
catch (Exception ex)
{
string viewError = JsonConvert.SerializeObject(ex);
return false;
}
}
public static bool InsertDataIntoDBF(string path)
{
try
{
string strLogConnectionString = "Provider=VFPOLEDB;Data Source=" + path + ";Collating Sequence=machine;Mode=ReadWrite;";
string query = "INSERT INTO CustomProperties(Public) VALUES (?)";
using (OleDbConnection connection = new OleDbConnection(strLogConnectionString))
{
connection.Open();
OleDbCommand cmdInit = new OleDbCommand("set null off", connection);
cmdInit.ExecuteNonQuery();
OleDbCommand command = new OleDbCommand(query, connection);
OleDbParameter publicStatus = command.Parameters.Add("Public", OleDbType.Char);
publicStatus.Value = "True";
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
catch (Exception ex)
{
log4net.LogManager.GetLogger("EmailLogger").Error(JsonConvert.SerializeObject(ex));
string viewError = JsonConvert.SerializeObject(ex);
return false;
}
}
public static bool CreateDBF()
{
...
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
...
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF"); // change 1
return true;
}
catch (Exception)
{
throw; //change2
}
}
public static bool InsertDataIntoDBF(string path)
{
try
{
...
}
catch (Exception)
{
throw; //change 3
}
}

c# - How can i check user(created or not created)

I'm working on MySql 5.6.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MySql.Data.MySqlClient;
namespace MySqlRank
{
class Sql
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public Sql()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "db";
uid = "root";
password = "pass";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Insert statement
public void Successful(ulong Id)
{
//if(NotCreated)
{
string query = "INSERT INTO rank(id, trades) VALUES('" + Id + "', '1')";
//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
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//else if (created)
{
string query = "UPDATE rank SET trades='1' WHERE id='" + Id + "'";
//Open connection
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
}
//Delete statement
public void Delete(ulong Id)
{
string query = "DELETE FROM rank WHERE id='"+ Id +"'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM rank";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["trades"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
}
}
My question on successful void.I try try-cath method but this isn't work.(Id is Unique Key).Afaik i'm need select method but i can't.My table name is rank(id, trade).I'm need if created update trades +1.if not created,create a new user.I'm only need check created or not created.
If I understand your question correct you want to check if the row already exist in your table? If so you can in your catch statement check for primary key violation:
catch(MySqlException ex)
{
this.CloseConnection();
if(ex.Number == 1067)
{
//Handle exception
}
}
EDIT: After testing your code on my own machine I found out that there is nothing wrong with this.OpenConnection(). And my code ran successfully. Are you sure that the credentials given to the connectionString are valid?

C# SSH tunnel to MySQL server

I am trying to write a simple program to connect to a MySQL remote server that can only be connected to via SSH.
It reports the SSH connects and that the port forwards but then states that it cannot connect to any of the specified hosts?
Have I configured this wrong?
Below is the console output and the code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Web;
using System.Windows.Forms;
//Add MySql Library
using MySql.Data.Entity;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
// SSH
using Renci.SshNet;
using Renci.SshNet.Common;
namespace MySQL_Console
{
class MainClass
{
public static void Main (string[] args)
{
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo ("mytestdb.co.uk", "root", "password123");
connectionInfo.Timeout = TimeSpan.FromSeconds (30);
using (var client = new SshClient(connectionInfo)) {
try
{
Console.WriteLine ("Trying SSH connection...");
client.Connect();
if (client.IsConnected)
{
Console.WriteLine ("SSH connection is active: {0}", client.ConnectionInfo.ToString());
}
else
{
Console.WriteLine ("SSH connection has failed: {0}", client.ConnectionInfo.ToString());
}
Console.WriteLine ("\r\nTrying port forwarding...");
var portFwld = new ForwardedPortLocal(Convert.ToUInt32(4479), "localhost", Convert.ToUInt32(3306));
client.AddForwardedPort(portFwld);
portFwld.Start();
if (portFwld.IsStarted)
{
Console.WriteLine ("Port forwarded: {0}", portFwld.ToString());
}
else
{
Console.WriteLine ("Port forwarding has failed.");
}
}
catch (SshException e)
{
Console.WriteLine ("SSH client connection error: {0}", e.Message);
}
catch (System.Net.Sockets.SocketException e)
{
Console.WriteLine ("Socket connection error: {0}", e.Message);
}
}
Console.WriteLine ("\r\nTrying database connection...");
DBConnect dbConnect = new DBConnect ("localhost", "test_database", "root", "passwrod123", "4479");
var ct = dbConnect.Count ("packages");
Console.WriteLine (ct.ToString());
}
}
// MySQL DB class
class DBConnect
{
private MySqlConnection connection;
private string server;
public string Server
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
private string database;
public string Database
{
get
{
return this.database;
}
set
{
this.database = value;
}
}
private string uid;
public string Uid
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
private string password;
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
private string port;
public string Port
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
//Constructor
public DBConnect(string server, string database, string uid, string password, string port = "3306")
{
this.server = server;
this.database = database;
this.uid = uid;
this.password = password;
this.port = port;
Initialize();
}
//Initialize values
private void Initialize()
{
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
Console.WriteLine("MySQL connected.");
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
default:
Console.WriteLine("Unhandled exception: {0}.", ex.Message);
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//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
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update(string tableName, List<KeyValuePair<string, string>> setArgs, List<KeyValuePair<string, string>> whereArgs)
{
string query = "UPDATE tableinfo SET name='Joe', age='22' WHERE name='John Smith'";
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Delete statement
public void Delete(string tableName, List<KeyValuePair<string, string>> whereArgs)
{
string query = "DELETE FROM tableinfo WHERE name='John Smith'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
//Select statement
public List<string> Select(string queryString)
{
string query = queryString;
//Create a list to store the result
List<string> list = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
int fieldCOunt = dataReader.FieldCount;
while (dataReader.Read())
{
for (int i = 0; i < fieldCOunt; i++) {
list.Add(dataReader.GetValue(i).ToString());
}
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
return list;
}
//Count statement
public int Count(string tableName)
{
string query = "SELECT Count(*) FROM " + tableName;
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");
//close Connection
this.CloseConnection();
return Count;
}
return Count;
}
//Backup
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(#"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException e)
{
Console.WriteLine("Error {0}, unable to backup!", e.Message);
}
}
//Restore
public void Restore()
{
try
{
//Read file from C:\
string path;
path = "C:\\MySqlBackup.sql";
StreamReader file = new StreamReader(path);
string input = file.ReadToEnd();
file.Close();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysql";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = string.Format(#"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();
}
catch (IOException e)
{
Console.WriteLine("Error {0}, unable to Restore!", e.Message);
}
}
}
}
Try specifying 127.0.0.1 instead of localhost, or more generally IPAddress.Loopback.ToString(). Also, you don't need to explicitly cast to uint32. So you should try something like:
var portFwld = new ForwardedPortLocal(4479, IPAddress.Loopback.ToString(), 3306);
If that doesn't work, try also specifying the server name, something like:
var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(), 4479, "servername_goes_here", 3306);

Connection leak in database class

I have a simple C# MySQL connection class as:
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Diagnostics;
using System.IO;
using MySql.Data.MySqlClient;
namespace FSB
{
public class DBConnect
{
private MySqlConnection connection;
private string server;
public string port;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
~DBConnect()
{
//close connection
this.CloseConnection();
}
//Initialize values
private void Initialize()
{
// Local Database
server = "localhost";
database = "mydatabase";
uid = "user";
password = "pass";
string connectionString;
connectionString = "SERVER=" + server + ";Port=" + port + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
public bool CloseConnection()
{
try
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
//Insert statement
public void Insert(String query)
{
//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
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update(string query)
{
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Delete statement
public void Delete(string query)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
public MySqlDataReader getRecord(string query)
{
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
reader = cmd.ExecuteReader();
return reader;
}
return null;
}
//Check Duplicate statement return true if not found
public bool checkDuplicate(string tableName ,String fieldName,String checkValue)
{
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
int rowCount = 0;
//Assign the query using CommandText
String query = "Select * from `" + tableName + "` Where `"+fieldName + "` = '"+ checkValue +"'";
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
reader = cmd.ExecuteReader();
while (reader.Read())
{
//get rows
rowCount++;
}
//close connection
this.CloseConnection();
if (rowCount > 0)
{
return false;
}
}
return true;
}
}
}
Can anyone please where I am losing the connection as the connection remains open even after the object is out of scope every time the i use to do any operation a new connection is created and a previous connection is not closed. so I am running out of the connection limit to mysql ?
I suggest you to use using blok in order to clean your non managed object, your connection in this sample
using (var connection = new MySqlConnection("..."))
{
....
}
Nota : using blok execute dispose in the end of treatment in roder to clean
public void Insert(String query)
{
using(var connection = new MySqlConnection("..."))
{
connection.Open();
using(var cmd = new MySqlCommand(query, connection))
{
cmd.ExecuteNonQuery();
}
}
}

Categories