I am a noob playing around with basic read, write and delete queries through C# into a MySQL Database. I am however stuck at the initial reading part. It appears that while reading the data from MySQL into a Data Grid View goes fine, however upon attempting to refresh the data it keeps populating the Grid with the same data (See photo) Unsure if this is originating from the Data Grid or the MySQL Dataset.
public partial class CBMain : Form
{
Connection con = new Connection();
private static ArrayList Listid = new ArrayList();
private static ArrayList ListItem = new ArrayList();
private static ArrayList ListDescription = new ArrayList();
private static ArrayList ListSerial = new ArrayList();
private static ArrayList ListQuantity = new ArrayList();
public CBMain()
{
InitializeComponent();
}
private void GetData()
{
try
{
con.Open();
string query = "select id, Item, Description, Serial, QuantityIn from TB_CB_StockIn";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
Listid.Add(row["id"].ToString());
ListItem.Add(row["Item"].ToString());
ListDescription.Add(row["Description"].ToString());
ListSerial.Add(row["Serial"].ToString());
ListQuantity.Add(row["QuantityIn"].ToString());
}
}
else
{
MessageBox.Show("Data not found");
}
con.Close();
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void updateDatagrid()
{
for (int i = 0; i < Listid.Count; i++)
{
DataGridViewRow newRow = new DataGridViewRow();
newRow.CreateCells(DGV_Stock);
newRow.Cells[0].Value = Listid[i];
newRow.Cells[1].Value = ListItem[i];
newRow.Cells[2].Value = ListDescription[i];
newRow.Cells[3].Value = ListSerial[i];
newRow.Cells[4].Value = ListQuantity[i];
DGV_Stock.Rows.Add(newRow);
}
}
private void BT_Refresh_Click(object sender, EventArgs e)
{
DGV_Stock.DataSource = null;
DGV_Stock.Rows.Clear();
DGV_Stock.Refresh();
GetData();
if (Listid.Count > 0)
{
updateDatagrid();
}
else
{
MessageBox.Show("Data not found");
}
}
}
Connection :
class Connection
{
MySql.Data.MySqlClient.MySqlConnection conn;
static string host = "*******";
static string database = "*******";
static string userDB = "*******";
static string password = "*******";
public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
public bool Open()
{
try
{
strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
conn = new MySqlConnection(strProvider);
conn.Open();
return true;
}
catch (Exception er)
{
MessageBox.Show("Connection Error ! " + er.Message, "Information");
}
return false;
}
public void Close()
{
conn.Close();
conn.Dispose();
}
public DataSet ExecuteDataSet(string sql)
{
try
{
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds, "result");
return ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public MySqlDataReader ExecuteReader(string sql)
{
try
{
MySqlDataReader reader;
MySqlCommand cmd = new MySqlCommand(sql, conn);
reader = cmd.ExecuteReader();
return reader;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public int ExecuteNonQuery(string sql)
{
try
{
int affected;
MySqlTransaction mytransaction = conn.BeginTransaction();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
affected = cmd.ExecuteNonQuery();
mytransaction.Commit();
return affected;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
}
Initial Data Read in Red, then after Refresh keeps populating
You never clear arraylist data so it will appear multiple times your click. My suggestion you should learn how to use arraylist.
Anyway, you should use only one arraylist and create object class instead to store those fields.
I am unable to find the problem here but this does not work! Any help will be appreciated.
It is a bool thing BTW.Every time i debug, it logs an error as follows
Invalid attempt to read when no data is present
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
//myReader.Read();
if (myReader["name"].ToString() != "" ) /* ( myReader["name"].ToString() != "" */
{
myReader.Read();
value = true;
}
}
catch (Exception ex)
{
//ErrorLabel.Text = ex.Message;
hiba.Visible = true;
hiba.Text = ex.Message + "\n Check Insert Call User Device ÁLERT!";
}
myReader.Close();
conn.Close();
return (value);
}
#andrew, kindly go through below code and let me know is it working for you or not?
string connectionString = "[YOUR_CONNECTION_STRING]";
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
if (myReader.Read())
{
if (myReader["name"].ToString() != "")
{
value = true;
}
}
}
catch (Exception ex)
{
}
myReader.Close();
conn.Close();
return (value);
}
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?
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}
How to stop database query during execution on button click.Is this is possible?I want to end database running query on logout.
SqlCommand.Cancel Method allows you to stop SQL running queries:
If there is nothing to cancel, nothing occurs. However, if there is a command in process, and the attempt to cancel fails, no exception is generated.
Here is code:
class Program
{
private static SqlCommand m_rCommand;
public static SqlCommand Command
{
get { return m_rCommand; }
set { m_rCommand = value; }
}
public static void Thread_Cancel()
{
Command.Cancel();
}
static void Main()
{
string connectionString = GetConnectionString();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Command = connection.CreateCommand();
Command.CommandText = "DROP TABLE TestCancel";
try
{
Command.ExecuteNonQuery();
}
catch { }
Command.CommandText = "CREATE TABLE TestCancel(co1 int, co2 char(10))";
Command.ExecuteNonQuery();
Command.CommandText = "INSERT INTO TestCancel VALUES (1, '1')";
Command.ExecuteNonQuery();
Command.CommandText = "SELECT * FROM TestCancel";
SqlDataReader reader = Command.ExecuteReader();
Thread rThread2 = new Thread(new ThreadStart(Thread_Cancel));
rThread2.Start();
rThread2.Join();
reader.Read();
System.Console.WriteLine(reader.FieldCount);
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}