Before anyone votes my question down, I would like to say that this is my first time using classes in C# and I have done a lot of research but I am still encountering errors. Newbie here.
I am trying to put the Insert, Delete, Update, and Count statements in a class file so that my code will be neat.
Here is the class file I made (with the help of research of course):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;
using System.Windows.Forms;
namespace classlib
{
public class DBConnect
{
private static MySqlConnection mycon;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
database = "restaurantdb";
uid = "user";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mycon = new MySqlConnection(connectionString);
}
private static bool OpenConnection()
{
try
{
mycon.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;
}
}
private static bool CloseConnnection()
{
try
{
mycon.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public static void Insert(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Update(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = mycon;
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Delete(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static int Count(string query)
{
int count = -1;
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
count = int.Parse(cmd.ExecuteScalar() + "");
CloseConnnection();
return count;
}
else
{
return count;
}
}
}
}
I was just trying the Count Method like in a certain form. Here is my code:
MessageBox.Show("NUMBER OF ACCOUNTS IN DATABASE = "+ DBConnect.Count("SELECT count(*) FROM usersettingsdb") +"", "CONFIRMATION");
But I get this error on the class file on the OpenConnection() method on the mycon.Open() line:
Object reference not set to an instance of an object.
How do I remove the said error and access the methods through calling it like so DBConnect.MethodName()?
I don't quite get anything about classes but I would really like to know how I can create my own functions/methods so as to keep my code neat.
Ok this is because you are messing up thing using in some cases static fields and in other cases not. There are tons of paper about static classes/members, see here for example.
The initialization code won't be called if you use the class as you are using.
In your case you should have a DBConnect instance and remove the static from methods
var db = new DBConnect();
and then use that in order to make queries:
db.Count(...);
Another solution is to call the Initialize method inside the Count method. You should modify Initialize in order to make it static (you will have to make all of your fields as static)
Another users will answer this question propably. So I want to mention different things. Your code is not very good. Instead of using it ,you can take a look at use of repository pattern. You can also use petapoco for database. These facilitate your work.
http://www.remondo.net/repository-pattern-example-csharp/
http://www.toptensoftware.com/petapoco/
Your myCon object is initialized in the Initialize() method, which is called in the constructor of the class, so only when you create an instance of DbConnect.
mycon = new MySqlConnection(connectionString);
In your code, you have no instance of DbConnect, you just call the static method Count of the class. So, the myCon is null.
Related
I have the following code to query the database, get the data, set each property for the object, and then return that object. In this case, it is an impact object that has the properties FinancialImpactId and EffectiveDate.
Throughout my project I query the database several times like the example below using objects that have the associated property name in the database.
Is there a way to create a generic reusable class that would take in the following parameters: object to be returned or the type, the connection, and the query text?
It would then return the object and set each property like below but dynamically and would be reusable.
try
{
using (var conn = new SqlConnection())
{
conn.ConnectionString = connection.ConnectionString;
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = " SELECT TOP 1 fi.financialimpactid,
fi.effectivedate " +
" FROM FinancialImpact fi " +
" INNER JOIN [Case] c ON c.caseid =
fi.caseid " +
" WHERE fi.isDeleted = 0 AND
c.IsDeleted = 0";
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
impact.FinancialImpactId = reader.GetInt32(0);
impact.EffectiveDate = reader.GetDateTime(1);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
An ORM like Entity Framework is certainly the better option here, but you can absolutely create a class that could query the database this way. You won't have parametrised queries or transactions, and you really won't save that much in re-usability, since every time you call it you'd need to provide lots of code to get it to function in the first place.
An example. Take a query class:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace QueryExample {
public class Query {
private readonly SqlConnection _connection;
public Query(SqlConnection connection) {
_connection = connection;
}
public IEnumerable<T> Run<T>(string text, Func<SqlDataReader, T> builder) {
var results = new List<T>();
try {
_connection.Open();
using (var command = new SqlCommand()) {
command.Connection = _connection;
command.CommandType = CommandType.Text;
command.CommandText = text;
var reader = command.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
results.Add(builder(reader));
}
_connection.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
}
return results;
}
}
}
...now take an example of running this class:
using System;
using System.Data.SqlClient;
namespace QueryExample {
public class Example {
public static void Run() {
using (var connection = new SqlConnection(string.Empty)) {
var query = new Query(connection);
const string text = "SELECT TOP 1 fi.financialimpactid, " +
"fi.effectivedate " +
" FROM FinancialImpact fi " +
" INNER JOIN [Case] c ON c.caseid = " +
"fi.caseid " +
" WHERE fi.isDeleted = 0 AND " +
"c.IsDeleted = 0";
var results = query.Run(text, GetData);
// do something with the results
}
}
private static Data GetData(SqlDataReader reader) => new Data {
FinancialImpactId = reader.GetInt32(0),
EffectiveDate = reader.GetDateTime(1)
};
}
internal class Data {
public int FinancialImpactId { get; set; }
public DateTime EffectiveDate { get; set; }
}
}
You see how running the class doesn't give you that much usability, especially since you will always have to return a result (making INSERT INTO, UPDATE and DELETE "result builders" more difficult to define), and it always has to be a list (not as big of a problem, but always having to do an empty check and accessing the first record can get old fast)?
This is one reason why you'd use an ORM nowadays. They not only simplify query creation, but also make parametrisation unnecessary.
Yo this is my first post here and i wanna know how to fix this problem in C#
so im tryin to connect to database and select information from it and those information will be displayed as a label ! easy,
so this is the error i get :
cannot access a non-static member of outer type 'windowsForm8.Form1'
via nested Type 'windowsForm8.Form1.DBConnect'
and this is the Code :
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;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
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)
{
//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:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
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 mytable (username, password) VALUES('shryder', 'nopassword')";
//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()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//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
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
please help me
,thanks :)
Move all your code from the class DbConnect yo your Form1 class. Then all of your methods have access to your form controls.
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;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
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)
{
//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:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
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 mytable (username, password) VALUES('shryder', 'nopassword')";
//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()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//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
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
Like this your code ahould be able to access the labels, so it should compile. It still doesn't do anything since none of the methods are called.
Edited this on my phone, so couldn't test the code.
Im very new on C#
I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.
this my code
Koneksi.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;
namespace timbangan
{
public class Koneksi
{
public MySqlConnection konek;
//string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public void bukaKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
var temp = konek.State.ToString();
if (temp == "Open")
{
MessageBox.Show(#"Connection working.");
}
else {
MessageBox.Show(#"Please check connection string");
}
}
public void tutupKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Close();
}
}//end of koneksi
}//end namespace
Isidata.cs File
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace timbangan
{
public class Isidata
{
MySqlDataAdapter adapter;
MySqlCommand komand;
Koneksi classKoneksi;
DataTable tabel;
string sql = "";
public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
classKoneksi = new Koneksi();
sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
//MessageBox.Show(sql);
tabel = new DataTable();
try
{
classKoneksi.bukaKoneksi();
komand = new MySqlCommand(sql);
adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
adapter.Fill(tabel);
}
catch (Exception)
{
MessageBox.Show("error");
}
return tabel;
}
}//end of issdata
}//end of timbangan
Form1.cs File
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
namespace timbangan
{
public partial class Form1 : Form
{
public DataTable tabel;
public string status = "";
public string berat_filter, qty, nama_barang, dari, shift;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Isidata isi = new Isidata();
tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
MessageBox.Show("Berhasil");
}
}
}
Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?
Thanks in advance
You could redesign your classes to something like this
namespace timbangan
{
public static class Koneksi
{
public static MySqlConnection konek;
private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public static MySqlConnection GetConnection()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
}
}//end of koneksi
public class Isidata
{
public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
sql = #"insert into tb_timbang
(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT)
values (#berat_filter,#qty,#nama_barang,#dari,#shift)";
try
{
using(MySqlConnection cnn = Koneksi.GetConnection())
using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
{
cmd.Parameters.Add("#berat_filter", MySqlDbType.VarChar).Value = berat_filter;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = qty;
cmd.Parameters.Add("#name_barang", MySqlDbType.VarChar).Value = nama_barang;
cmd.Parameters.Add("#dari", MySqlDbType.VarChar).Value = dari;
cmd.Parameters.Add("#shift", MySqlDbType.VarChar).Value = shift;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex.Message);
return -1;
}
}
}
}//end of issdata
}//end of timbangan
In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections
The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class
As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum
Make a class named DBClass.cs and write the below code-
class DBClass
{
MySqlCommand odcmd = new MySqlCommand();
MySqlConnection odcon = new MySqlConnection();
MySqlDataAdapter oda = new MySqlDataAdapter();
public DBClass()
{
}
public void OpenConnection()
{
odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
if (odcon.State == ConnectionState.Closed)
odcon.Open();
oda.SelectCommand = odcmd;
odcmd.Connection = odcon;
}
public void CloseConnection()
{
if (odcon.State == ConnectionState.Open)
odcon.Close();
}
public DataTable Select(string sql)
{
DataTable dt = new DataTable();
odcmd.CommandText = sql;
oda.Fill(dt);
return dt;
}
public int ModiFy(string sql)
{
odcmd.CommandText = sql;
return odcmd.ExecuteNonQuery();
}
}
On your form, Now you can fire your query like-
DbclassObject.Modify(Your_Insert_Update_Delete_Query);
DataTable dt= DbclassObject.Select(Your_Select_Query);
I do have a problem in checking username and password in my registration form. When I tend to register the same username and password that's is already in my database(Access), still it allows to register. I just wanna trap it however, I don't know how to that.
What I want to output is that, I want a trap that says "Account Exists, Try Again!" or "Username Exists!"
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; using System.Text.RegularExpressions;
namespace Login { public partial class Register : Form {
private OleDbConnection personalConn;
private OleDbCommand oleDbCmd = new OleDbCommand();
private String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public Register()
{
personalConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
if (textBox1.Text != "" && textBox2.Text != "")
{
int temp;
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
personalConn.Close();
}
}
catch (Exception)
{
MessageBox.Show("Invalid!, Duplicate Data.");
}
}
Notes: textBox1= username
textBox2= password Your attention is much highly appreciated. Thank you so much in advance.
Here is code which uses oledbcommand parameters using ? placeholder as mentioned in MSDN Reference. Also I have added using block which should Close opened connection implicitly.
using(OleDbConnection con = new OleDbConnection(connParam))
using(OleDbCommand cmd = new OleDbCommand("select count(*) from data where Users = ?"))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
object objRes = cmd.ExecuteScalar();
if (objRes == null || (int)objRes == 0)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO data (Users,Pass) values(?, ?);";
cmd.Parameters.AddWithValue("#Users", textBox1.Text);
cmd.Parameters.AddWithValue("#Pass", textBox2.Text);
int iRes = cmd.ExecuteNonQuery();
if(iRes > 0)
MessageBox.Show("Registration Success!");
}
else
errorProvider2.SetError(textBox1, "This username has been using by another user.");
}
You almost never use data (in this case, a username) as the primary key for a record in a database. Chance are, your access database is set up the same way.
This means that there is nothing at the DBMS layer that will stop this from occurring, short of making the username the primary key (not recommended).
The solution is to perform a SELECT query to get the count of records with that username, and only allow the insert if the count is 0. You might be able to write a trigger to do this for you, and make the DBMS "reject" the insert, but given your (apparent) level with databases, I wouldn't try that at this point.
To get the count:
SELECT Count(*) FROM Users WHERE userName=#userName
A paramaterized query here is crucial to protect against SQL injection.
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;
using System.Text.RegularExpressions;
namespace Login
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(text1Box1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Mandatory fields password or user is empty");
retrun; //I'm not sure if this return is need. Remove it if MessageBox "breaks" the execution of the code below.
}
OleDbCommand cmd = new OleDbCommand(#"Select * from Data where User=#User");
cmd.Parameters.AddWithValue("#User", textBox1.Text);
DataSet dst = SqlManager.GetDataSet(cmd, "Data");
if(dst.Tables[0].Rows > 0)
{
MessageBox.Show("User already exist");
return; //again i'm not sure that this return is needed.
}
Insert("Data", "User", textBox1.Text, "Pass", textBox2.Text);
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need 1 class make it SqlManager.
public class SqlManager
{
private String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public static GetOleDbConnection(OleDbCommand cmd)
{
if(cmd.Connection == null)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
Here is another method you can put in the form class:
public virtual void Insert(string TableName, params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
OleDbCommand cmd = new OleDbCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
Like other guys tell you use parameters in this case you will avoid sql injection. Read in wikipedia about it. Also I add some structure for your program, it is not perfect but I should write a lot for more. It is possible to have some typos here, because I wrote the code here. How you make the check, you fetch the data from database for the user which you write in textbox1.Text. If the dataSet have rows that means at the moment there is existing user with this name. If you don't know what is data set read System.Data.
You should learn to write data access in other classes !
Try this with your Existing Code :
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "') SELECT '" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "' WHERE NOT EXISTS(SELECT Users,Pass FROM data WHERE Users='" + this.textBox1.Text.ToString() +"');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
else
{
MessageBox.Show("Username is already Present !!!");
}
It returns 0 if the username is already present in data.
If in php we can do something like where $result is some query:
$result = mysql_query("SELECT * FROM student");
if (mysql_num_rows($results) !==0)
{
//do operation.
}
else
echo "no data found in databasae";
What is equivalent to this if I want to do this in C# language?please advise.
I have Created a full Console application using mysql. In your select query you are querying the whole table which is a bad idea. use limit to get only one result - this should be enough to determine if there are any rows in the table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
if (AnyRows())
{
Console.WriteLine("There are rows in the database");
}
else
Console.WriteLine("no data found in database");
//This will pause the output so you can view the results. Otherwise you will see the dos screen open then close.
Console.Read();
}
//This is the Methos to call
public static bool AnyRows()
{
string connectionString = "Server=localhost;Database=test;Uid=root;Pwd=yourpassword;";
//Wrap this is using clause so you don't have to call connection close
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "select * from mytable limit 1";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
MySqlDataReader reader = command.ExecuteReader();
return reader.HasRows;
}
}
}
}
}
assuming "results" is of type int
if(results != 0)
{
//do operation
}
else
{
Console.WriteLine("..."); //or output elsewhere
}
c# if else
add a reference to linq, and it gets really easy
var result = SomeDatabaseCall();
if (result.Any()){
// do something
}
if you want to filter the results even further, you can do that inside the Any
var result = SomeDatabaseCall();
if (result.Any(r => r.ID == SomeID)){ // ID can be replaced with any properties in your return model
// do something
}
I got the solution. It is actually very simple. BTW thanks for those who helping. This is the solution:
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "your_server";
database = "your_db";
uid = "usr";
password = "pwd";
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)
{
//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:
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;
}
}
public void Select()
{
string query = "SELECT * FROM table";
//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 in the database
if (dataReader.HasRows == true)
{
while (dataReader.Read())
{
//do retrieve data
}
}else
{
MessageBox.Show("There's no recods in the database");
}
}
}
}
It's best to use SELECT 1 instead of grabbing unnecessary data from the database to simply check for the existence of rows.
public static bool IsTableEmpty(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT 1 FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
using (var reader = cmd.ExecuteReader())
{
return !reader.HasRows;
}
}
}
}
If you want to get the row count, then you'll need something like:
public static int GetTableRowCount(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT COUNT(*) FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
return Convert.ToInt32(cmd.ExecuteScalar());
}
}
}