As part of a project I'm putting together, I have an Arduino updating a MySQL database via C♯ and, in another location I have another C♯ program doing a simple SELECT query on the database, and communicating its findings to another Arduino via Serial. I have written most of the code for this second program but am having some annoying issues at the end of it all.
Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Xml;
using System.IO.Ports;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string hkday;
string hkall;
//SERIAL
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.NewLine = "\n";
//OPEN SERIAL
serialPort1.Open();
//SQL
string connString = "Server=xxxx;Uid=xxxx;Password=xxxx;Port=xxxx;Database=xxxx;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command1 = conn.CreateCommand();
command1.CommandText = "Select USERS from HK where UPTIME='HKDAY'";
MySqlCommand command2 = conn.CreateCommand();
command2.CommandText = "Select USERS from HK where UPTIME='HKALL'";
//EXECUTE QUERIES
if (_continue = true)
{
conn.Open(); //Connect
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
//Write to value and string
Console.WriteLine(reader1["USERS"].ToString());
hkday = reader1["USERS"].ToString();
}
Console.ReadLine();
_continue = false;
conn.Close(); //Disconnect
}
else
{
conn.Open(); //Connect
MySqlDataReader reader2 = command1.ExecuteReader();
while (reader2.Read())
{
//Write to console and string
Console.WriteLine(reader2["USERS"].ToString());
}
hkall = reader2["USERS"].ToString();
Console.ReadLine();
_continue = true;
conn.Close(); //Disconnect
//WRITE STRINGS TO SERIAL
serialPort1.WriteLine(
String.Format(hkday, hkall));
}
serialPort1.Close();
}
public static bool _continue { get; set; }
}
}
I can't work out how my section titled WRITE STRINGS TO SERIAL needs to be syntaxed and placed within the code to be able to reference both 'hkday' and 'hkall'
My 'if (_continue = true)' flag doesn't seem to work, and I'm not sure why.
I think that if these two issues are solved, the program ought to work, can you see any other glaring issues?
Thank you, I know these are only tiny issues, but I can't seem to work them out.
Potentially important: I'm trying to get the output as '123,456\n' as my arduino program already recognises this as its input.
UPDATE
Having received the answers I have, I have compounded this project with the other one I'm currently doing to try and have an arduino update a MySQL database via C# and then also have it download the table's data that it isn't updating to display out through another arduino.
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 System.IO.Ports;
using MySql.Data.MySqlClient;
namespace SQL_Scraper
{
public partial class Sandro : Form
{
//Serial Settings
SerialPort UNO = new SerialPort("COM4", 9600);
SerialPort MEGA = new SerialPort("COM3", 9600);
//Incoming Data String
string RxString;
//Int for download
int? vnday = 0;
int? vnall = 0;
public Sandro()
{
InitializeComponent();
//Open UNO port
UNO.Open();
//Open MEGA Port
MEGA.Open();
}
private void MEGA_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
}
private void Sandro_FormClosing(object sender, FormClosingEventArgs e)
{
if (UNO.IsOpen | MEGA.IsOpen)
{
UNO.Close();
MEGA.Close();
}
}
private void DisplayText(object sender, EventArgs e)
{
}
private void Begin_Click(object sender, EventArgs e)
{
//Turn off start button
Begin.Enabled = false;
//?
this.Invoke(new EventHandler(DisplayText));
//Create Event Handler if data is receiverd
MEGA.DataReceived += new SerialDataReceivedEventHandler(MEGA_DataReceived);
string SQLString = "Server=benchmarkcount.db.9506323.hostedresource.com;Uid=benchmarkcount;Password=Watercress2428;Port=3306;Database=benchmarkcount;";
MySqlConnection SQLConnection = new MySqlConnection(SQLString);
//Receive data
RxString = MEGA.ReadExisting();
//Append Serial Input to Output box)
outputBox.AppendText(RxString);
//Get Unsaved input from text box
string input = outputBox.Text;
string[] inputLines = input.Split('\n');
//Upload findings from MEGA to SQL
foreach (string line in inputLines)
{
if (line.EndsWith("\r")) //Makes sure line is complete
{
if (line.StartsWith("Today's total users: "))
{
string dayUsers = line.Substring(20).Trim();
MySqlCommand UpdateHKDAY = SQLConnection.CreateCommand();
UpdateHKDAY.Parameters.AddWithValue("param1", dayUsers);
UpdateHKDAY.CommandText = "UPDATE HK SET USERS=?param1 WHERE UPTIME='HKDAY'";
SQLConnection.Open();
UpdateHKDAY.ExecuteNonQuery();
SQLConnection.Close();
}
else if (line.StartsWith("All-time total users: "))
{
string allUsers = line.Substring(21).Trim();
MySqlCommand UpdateHKALL = SQLConnection.CreateCommand();
UpdateHKALL.Parameters.AddWithValue("param2", allUsers);
UpdateHKALL.CommandText = "UPDATE HK SET USERS=?param2 WHERE UPTIME='HKALL'";
SQLConnection.Open();
UpdateHKALL.ExecuteNonQuery();
SQLConnection.Close();
}
}
}
//Only keep unparsed text in text box
outputBox.Text = inputLines[inputLines.Length - 1];
//Download Numbers Query
MySqlCommand DownUsers = new MySqlCommand("Select USERS, UPTIME from VN where UPTIME IN ('VNDAY', 'VNALL')", SQLConnection);
//Open Connection
SQLConnection.Open();
//Execute Downloading Numbers
MySqlDataReader theResults = DownUsers.ExecuteReader();
while (theResults.Read())
{
switch (theResults["UPTIME"] as string)
{
case "VNDAY":
vnday = theResults["USERS"] as int?;
break;
case "VNALL":
vnall = theResults["USERS"] as int?;
break;
}
}
//Do things with the results
UNO.WriteLine(String.Format("{0},{1}", vnday, vnall));
Console.WriteLine(String.Format("{0},{1}", vnday, vnall));
//Close Connection
SQLConnection.Close();
}
private void Sandro_Load(object sender, EventArgs e)
{
}
private void Cease_Click(object sender, EventArgs e)
{
Begin.Enabled = true;
Cease.Enabled = false;
}
}
}
However, I would like to be able to check this data - the data being sent to the arduino - in my inputBox to make sure it's in the format "vnday, vnall\n"
Your question and example has too many contradictions. It appears that you are under impression that there is static persistence between separate app runs. There isn't. All your static variables will be cleared with each run. It would be different if you had a method that you called in a loop inside the same app domain.
Also, judging by your variable names and your output requirement, the USERS field is a numeric.
So, assuming you have following table:
USERS UPTIME
------ ------
123456 HKALL
234567 HKDAY
following code:
public static void Main()
{
int? hkday = 0;
int? hkall = 0;
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS, UPTIME from HK where UPTIME IN ('HKDAY', 'HKALL')", conn);
MySqlDataReader reader = cmd.ExecuteReader();
//this assumes that there is only one record per 'HKDAY' and 'HKALL',
//otherwise the last value will be stored
while (reader.Read())
{
switch (reader["UPTIME"] as string)
{
case "HKDAY":
hkday = reader["USERS"] as int?;
break;
case "HKALL":
hkall = reader["USERS"] as int?;
break;
}
}
}
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
will output:
234,567
123,456
Or if you desire to run independent queries:
private static int? GetUSERS(string hkval)
{
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS from HK where UPTIME=#hkval", conn);
cmd.Parameters.AddWithValue("hkval", hkval);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
return reader["USERS"] as int?;
return null;
}
}
public static void Main()
{
int hkday = (int)GetUSERS("HKDAY");
int hkall = (int)GetUSERS("HKALL");
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
You could also pass HKDAY/HKALL as a parameter to you app using args.
I'm not a C programmer but know a lot of serial ports, I suppouse that this solves your first issue.
//WRITE STRINGS TO SERIAL
serialPort1.Write(hkday); // do not append line feed
serialPort1.WriteLine(hkall); // append line feed
Related
I have a need to connect to a report Interbase server and pull data from a table.
I have the following code, I am trying several options to make a successful connection to the server, however not able to do so. Could you please let me know what's wrong with my code. Or please point me to any article which shows a step by step approach to successfully connect to an Interbase server and pull data.
using System;
using System.Data;
using System.Data.Common;
using InterBaseSql.Data.InterBaseClient;
string connectionString = "server=remoteserver_ip_address;dataBase=C:\\test\\interbasedb\\database.gdb;User_Name=myusername;Password=mypassword;";
using (var connection = new IBConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from table rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
I suspect the issue is with the connection string. I tried changing the connection string several ways, but getting different error every time.
All errors below.
Client library - ibclient64 not found (I copied ibclient64.dll into the project folder, and this error was resolved)
Your user name and password are not defined. Ask your database administrator to set up a InterBase login.
connection rejected by remote interface
Unable to complete network request to host "remoteserver_ip_address". Failed to locate host machine. Undefined service gds_db/tcp.
I am able to connect to the same server using IBConsole application, Which I believe is a client software to connect to Interbase server (Like Management Studio for SQL Server, and WorkBench for MySQL and PGAdmin for PostgresSQL)
The Parameters I am using to connect to the Interbase Server using IBConsole are same as that of I am using in the C# code.
Report Server IP: remoteserver_ip_address
DataBase: C:\test\interbasedb\database.gdb
User Name: myusername
Password: mypassword
Partial breakthrough for above issue.
After several hours of trial and error, I was finally able to connect to the interbase server successfully using Embarcadero drivers.
I had to change the connectionstring to look as below for a successful connection.
server=remoteserver_ip_address;database=C:\test\interbasedb\database.gdb;user=myusername;password=mypassword
But now I am stuck with another issue. When I use a query like select * from some_table_which_doesnot_exists, I clearly receive a message that the Table is not found.
And when I use a query like Select * from a table_that_exists_in_the_db, I always get follow error.
Dynamic SQL Error
SQL error code - 804
SQLDA error (I believe SQLDA = SQL DataAdapter, because thats where the code it throwing error)
I went to the Embarcadero Error Codes List to see more information on this error and found the reason to be SQLDA missing or incorrect version, or incorrect number/type of variables.. I am stuck here not sure how to proceed further. Please help.
I think you are missing "PORT" details for connection to the interbase server instance.
You can try the below solution for the connection string. This has worked for me in my local machine.
static void Main(string[] args)
{
var cs = BuildConnectionStringBuilder().ToString();
try
{
using (var connection = new IBConnection(cs))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from employee rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private static IBConnectionStringBuilder BuildConnectionStringBuilder()
{
var builder = new IBConnectionStringBuilder();
builder.UserID = "SYSDBA";
builder.Password = "masterkey";
builder.DataSource = "localhost";
builder.Database = AppDomain.CurrentDomain.BaseDirectory + "test-employee.ib";
builder.Port = 3050;
return builder;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1_3grupa
{
public partial class Form1 : Form
{
SqlConnection konekcija = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void buttonIzadji_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
string sqlUpit = "select * from Citalac";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
//MessageBox.Show("Greska");
}
}
private void buttonPrikazDGV_Click(object sender, EventArgs e)
{
SqlParameter param = new SqlParameter();
param.ParameterName = "#param1";
param.Value = numericUpDown1.Value;
string sqlUpit = "select * from Hotel where HotelID=#param1";
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
komanda.Parameters.Add(param);
try
{
konekcija.Open();
SqlDataReader dr = komanda.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
}
catch (Exception)
{
MessageBox.Show("Greska");
}
finally
{
konekcija.Close();
}
}
private void buttonPrikazLV_Click(object sender, EventArgs e)
{
string sqlUpit = "select * from Hotel";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listItem.SubItems.Add(row["Drzava"].ToString());
listItem.SubItems.Add(row["Kategorija"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
MessageBox.Show("Greska");
}
}
private void buttonIzadji2_Click(object sender, EventArgs e)
{
this.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
I want to make my txtSearch textbox in Visual Studio autocomplete.
I have searched around for a long time, for some explanations and tutorials,
but the most are about SQL databases. I have a MS Access database in my application.
I want to make autocomplete suggests from my Titel colon in my database (appData/Film)
First of all, can a textbox do the job, or is a rich textbox necessary to do the job?
I don't expect code from you, but maybe an explanation or a tutorial, you know somewhere?
Thanks. And oops. Important info: My application is based on C#, and coded in Visual Studio.
Try it this way.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace WinAutoComplete
{
public partial class Form1 : Form
{
AutoCompleteStringCollection ProductList = new
AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string
string cnString = #"Data Source=EXCEL-PC\SQLEXPRESS; Initial Catalog=NORTHWND;" +
"Trusted_Connection = True";
/*use following if you use standard security
string cnString = #"Data Source=(local);Initial
Catalog=northwind; Integrated Security=SSPI"; */
//declare Connection, command and other related objects
SqlConnection conGetData = new SqlConnection(cnString);
SqlCommand cmdGetData = new SqlCommand();
SqlDataReader drGetData;
try
{
//open connection
conGetData.Open();
//prepare connection object to get the data through
//reader and populate into dataset
cmdGetData.CommandType = CommandType.Text;
cmdGetData.Connection = conGetData;
cmdGetData.CommandText = "Select ProductName From Products";
//read data from command object
drGetData = cmdGetData.ExecuteReader();
if (drGetData.HasRows == true)
{
while (drGetData.Read())
ProductList.Add(drGetData["ProductName"].ToString());
}
else
MessageBox.Show("No data found in Products tables");
//close reader and connection
drGetData.Close();
conGetData.Close();
//set the default pattern to SuggestAppend
//comboBoxPattern.SelectedIndex = 1;
txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtProductID.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtProductID.AutoCompleteCustomSource = ProductList;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//check if connection is still open then attempt to close it
if (conGetData.State == ConnectionState.Open)
{
conGetData.Close();
}
}
}
private void comboBoxPattern_SelectedIndexChanged(object sender, EventArgs e)
{
//switch (comboBoxPattern.Text)
//{
// case "Suggest":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Suggest;
// break;
// case "Append":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Append;
// break;
// case "SuggestAppend":
// txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
// break;
//}
}
}
}
This definitely works, as you can see in the screen shot below.
Also, check this out when you have a chance.
https://www.connectionstrings.com/
I would like to add some information to my database. I searched for some tutorials, but none of them work.
NonQuery can do what he needs to do, because the messagebox returns "Success" (1). But it does not update my database. If I put the same query to "Add New Query", directly to my database, it works.
Can someone help me?
My class code at the moment:
namespace BurnThatFat
{
class databaseconnection
{
//fields
SqlConnection connection;
string connectionstring;
public databaseconnection()
{
// fields waarde toewijzen
connectionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;" +
#"AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
connection = new SqlConnection(connectionstring);
OpenConnection();
CloseConnection();
}
public List<Object> getObjectsFromDatabase()
{
try
{
OpenConnection();
// sql query
// Datareader
// sqlcommand
// return list van objecten , objecten veranderd naar jouw wens van data.
CloseConnection();
}
catch (Exception)
{
throw;
}
return new List<object>();
}
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;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (connection)
{
SqlCommand command = new SqlCommand(query, connection);
OpenConnection();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
}
Edit:
And this is the code for my buttons etc:
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;
// voor sql connectie.
using System.Data.SqlClient;
namespace BurnThatFat
{
public partial class SignUp : Form
{
databaseconnection db = new databaseconnection();
public SignUp()
{
InitializeComponent();
gb_login.Visible = false;
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = false;
gb_email.Visible = false;
gb_Start.Visible = true;
}
private void btn_SignUp_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_Voornaam.Visible = true;
}
private void btn_login_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_login.Visible = true;
}
private void btn_loginvolgende_Click(object sender, EventArgs e)
{
gb_login.Visible = false;
// hier moet nog een GB!!!!!!
}
private void btn_voornaamvolgende_Click(object sender, EventArgs e)
{
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = true;
}
private void btn_achternaamvolgende_Click(object sender, EventArgs e)
{
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = true;
}
private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
{
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = true;
}
// einde registratie
// opslaan van gegevens in database
private void btn_emailvolgende_Click(object sender, EventArgs e)
{
// gebruiker = new Gebruikerklasse();
// gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
//// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
// gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
/// gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
// gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
// gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
/// gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
// gebruiker.Email = Convert.ToString(tb_email.Text);
// gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);
db.AddGebruiker();
gb_email.Visible = false;
// hier moet nog een GB!!!!!
}
private void btn_gewichtvolgende_Click(object sender, EventArgs e)
{
gb_gewicht.Visible = false;
gb_email.Visible = true;
}
}
}
The simplest way to insert into a SQL Server database:
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
As long as commandText is a working query, it should insert a row. It would be better to use parameters for your values instead of hard coding them like I did here - that avoids SQL injection attacks and other potential problems. You can search Google for that (or the question you are asking now) and find tons of resources to help you.
If you need more specific help, post details such as what is actually happening when you try to run your code - are you getting an exception?
I'd clean up a bunch of things before doing anything else.
First, get rid of the openconnection and closeconnection methods all together. And don't keep an instance property for the connection in your class. Create the connection ondemand with a using statement, because at the end of the using statement the compiler will insert a call to the Dispose method on the connection's IDisposable interface implementation and it will close the connection automatically for you.
So after cleaning up all the unnecessary code all you really should have in this class is an implementation of your Addgebrukier method which would look like this
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
You should also load your connection string from the section in the app/web.config, but you can do that later after you get it running.
Here is a simple concept that should work perfectly fine for you. Just change the ServerName, DatabaseName, etc.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
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'm doing like a Mcdonalds' control panel to choose
what clients want to take. I'm doing it with Windows Forms
using C#. What I made was creating a class called products
and after in Form1.cs I made a List where I'll put the
products read from database.
I managed to do this and show the results on a DataGrid.
My problem is that when I make the selection of the products
and then I click on the button Send, the Datagrid doesn't refresh automatically. I have to close the program and when
i restart it i can see the changes.
My question is, does anyone know how to update de Datagrid
whitout restarting the program?
Thanks very much, I add my code below:
![]My_windows_form1
#
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 MySql.Data.MySqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
MySqlConnection conn = new MySqlConnection();
String connectionString = "Server=127.0.0.1; Database=mydatabase; Uid=root; Pwd=;";
List<products> listproducts = new List<products>();
public string product;
public string quantity;
public Form1()
{
InitializeComponent();
startConn();
}
private void startConn()
{
try
{
conn.ConnectionString = connectionString;
conn.Open();
textBox3.Text= "Correct connection";
//we call the function READ
read();
}
catch (MySqlException)
{
textBox3.Text="An error has ocurred";
}
}
public void read()
{
MySqlCommand instruccio = conn.CreateCommand();
instruccio.CommandText = "Select * from products";
MySqlDataReader search = instruccio.ExecuteReader();
while (search.Read())
{
products prod = new products();
prod.IdProd = search["idProd"].ToString();
prod.Name = search["nomProd"].ToString();
prod.Quantity = Int32.Parse(search["quantitat"].ToString());
listproducts.Add(prod);
}
dataGridView1.DataSource = listproducts;
search.Close();
search.Dispose();
}
private void btnEnviar_Click(object sender, EventArgs e) //Button Send (Enviar in spanish)
{
try
{
//before updating the stock in database we query the total quantity of the product selected
MySqlCommand instruccio1 = connexio.CreateCommand();
instruccio1.CommandText = "Select quantitat from productes where `nomProd`='"+ this.product +"'";
MySqlDataReader read = instruccio1.ExecuteReader();
int result = 0;
while (read.Read())
{
resultat=Int32.Parse(read["quantitat"].ToString());
}
read.Dispose();
instruccio1.Dispose();
if (this.quantity != 0)
{
if (result > this.quantity)
{
int difference = result - this.quantity;
MySqlCommand instruccio2 = conn.CreateCommand();
instruccio2.CommandText = "UPDATE products set `quantitat`='" + this.difference + "' where products.nomProd='" + this.product + "'";
instruccio2.ExecuteNonQuery();
conn.Close();
startConn();
textBox1.Text= "";
textBox2.Text = "";
this.quantity = "";
this.product = "";
}
else
{
MessageBox.Show("There's no quantity.");
}
}
catch (Exception xe)
{
MessageBox.Show("",xe.Message);
}
}
private void btnEsborrar_Click(object sender, EventArgs e) //Erase button
{
this.quantity = "";
this.product = "";
this.aEnviar = 0;
textBox1.Text = quantity;
textBox2.Text = product;
}
....
....
what you can do is the following:
Add a timer control on your form and set the time you want its Tick event to be fired, it is put in the Interval property in milliseconds.
on this event call your function startConn.
and thats it, very easy :)
In your read() method before
dataGridView1.DataSource = listproducts;
add
dataGridView1.DataSource = null;
Then call your startConn() method whenever you want.