I have a small problem with the c# DataRow Command in my code. Because when im trying to loop trough my mysql database and i have the foreach like this:
foreach (DataRow row in _login._database)
{
//And search for Username and Pass that match
if (row.ItemArray[0].Equals(username) && row.ItemArray[1].Equals(password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
break;
}
//If not, then show this message.
else
{
MessageBox.Show("Username/Password incorrect");
break;
}
}
This error will come up:
Error 1 Cannot convert type 'char' to 'System.Data.DataRow'
Can someone help/explain to me what im doeing wrong.
This is the rest of the code:
namespace Chat
{
public partial class StartupForm : Form
{
private LoginConnect _login = new LoginConnect();
public StartupForm()
{
InitializeComponent();
_login.OpenConnection();
}
private void _loginButton_Click(object sender, EventArgs e)
{
string username = _usernameTextBox.Text;
string password = HashPass(_passwordTextBox.Text);
//Loop through database
foreach (DataRow row in _login._database)
{
//And search for Username and Pass that match
if (row.ItemArray[0].Equals(username) && row.ItemArray[1].Equals(password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
break;
}
//If not, then show this message.
else
{
MessageBox.Show("Username/Password incorrect");
break;
}
}
_login.LoginQuery(username, password);
}
private void button1_Click(object sender, EventArgs e)
{
var register = new RegisterForm();
register.ShowDialog();
}
public string HashPass(string password)
{
MD5 mdvijf = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
mdvijf.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
//get hash result after compute it
byte[] result = mdvijf.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
}
}
LoginCOnnect.cs:
namespace Chat
{
class LoginConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
public string _database;
private string _uid;
private string _password;
//public String MessageRecieved;
private StringList _messagelist = new StringList();
//private string _table = "logingegevens";
private string _port;
//private bool succes = false;
public LoginConnect()
{
Initialize();
}
public void Initialize()
{
_server = "localhost";
_port = "3307";
_database = "testlogin";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
public void LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
int count = 0;
while (dataReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Login Succesfull");
}
else if (count > 1)
{
MessageBox.Show("Acces denied");
}
else
{
MessageBox.Show("Username or passowrd is not correct.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The problem is that in this statement
foreach (DataRow row in _login._database)
you are looping through a string, and so the enumeration of _login._database is an IEnumerable of chars and not of DataRow, so row variable would be a char and not a DataRow.
I suggest you to retrieve the data into an internal DataTable, your LoginConnect code would be like this:
namespace Chat
{
class LoginConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
public string _database;
private string _uid;
private string _password;
private StringList _messagelist = new StringList();
private string _port;
private DataTable _dataTable;
public LoginConnect()
{
Initialize();
}
public DataTable Data
{ get { return _dataTable; } }
public void Initialize()
{
_server = "localhost";
_port = "3307";
_database = "testlogin";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
public void LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
_dataTable = new DataTable();
adp.Fill(_dataTable);
var count = _dataTable.Rows.Count;
}
catch{}//your handling
}
}
}
So you can loop through Data:
foreach (DataRow row in _login.Data.AsEnumerable())
THis line is wrong: (DataRow row in _login._database because _database is type of string. You have to iterate over something that have DataRow like DataTable.
Anyway I would change your code to this:
private void _loginButton_Click(object sender, EventArgs e)
{
string username = _usernameTextBox.Text;
string password = HashPass(_passwordTextBox.Text);
if (_login.LoginQuery(username, password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
}
else
{
MessageBox.Show("Username/Password incorrect");
}
}
and LoginCOnnect.cs method LoginQuery to return bool
public bool LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
int count = 0;
while (dataReader.Read())
{
count = count + 1;
}
if (count == 1)
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
Related
I connected SQL server database and I using username and password value return xml boolean true. But I want to get sicilKod value according to the results of the username query. How can I do it?
This returning boolean value according to username and password
[WebMethod]
public bool login(string unamePI, string passPI)
{
DataTable mytable = new DataTable();
bool mydeger = false;
mytable = GetTableWithQueryParams("select * from UYE where USERNAME ={0} and PASSWORD={1}", unamePI, passPI);
if (mytable.Rows.Count > 0)
{
mydeger = true;
}
else
{
return mydeger;
}
string de = mytable.Rows[0].ToString();
return mydeger;
}
Database connect:
public static DataTable GetTableWithQueryParams(string SQLCommandText, params object[] myParametres)
{
string aConnectionString = "Data Source = ..; Initial Catalog = mydatabase; Persist Security Info = True; User ID = ..; Password = ..";
SqlConnection SqlConn = new SqlConnection(aConnectionString);
SqlCommand MyCommand = new SqlCommand("", SqlConn);
DataTable MyTable = new DataTable();
try
{
int i = 0;
SqlConn.Open();
foreach (object MyObject in myParametres)
{
if (SQLCommandText.Contains("{" + i.ToString() + "}"))
{
SQLCommandText = SQLCommandText.Replace("{" + i.ToString() + "}", "#Prm" + i.ToString());
MyCommand.Parameters.AddWithValue("Prm" + i.ToString(), MyObject);
i++;
}
}
MyCommand.CommandText = SQLCommandText;
SqlDataReader MyReader = MyCommand.ExecuteReader();
MyTable.Load(MyReader);
SqlConn.Close();
MyReader.Dispose();
}
catch (Exception ex)
{
throw new Exception(SQLCommandText + "\n" + ex.Message);
}
finally
{
SqlConn.Dispose();
MyCommand.Dispose();
}
return MyTable;
}
change your method to this.
public string login(string unamePI, string passPI)
{
DataTable mytable = new DataTable();
string result = "";
mytable = GetTableWithQueryParams("select * from UYE where USERNAME ={0} and PASSWORD={1}", unamePI, passPI);
if (mytable.Rows.Count > 0)
{
result = string.Format("Welcome {0}", mytable.Rows[0]["sicilKod"].ToString());
}
return result;
}
then check if login method return value is empty or not.
I am currently trying to learn MySQL with C# and I've been having some problems.
string currServer = w.server.Text;
string currDatabase = w.database.Text;
string currUser = w.uid.Text;
string currPassword = w.password.Text;
server = currServer;
database = currDatabase;
uid = currUser;
password = currPassword;
This here gives me the error That I'm not allowed to connect to that host. But when I use
server = "localhost";
database = "test";
uid = "root";
password = "test123";
I am able to connect to the server. I've tried to create a new MySQL user and been Googling around a bit.
And I also have this error when I want to access my Query class to run queries I've get the error: Connection must be valid or open.
When I use the same method in the db_connection class this does not appear.
Query.cs file:
public void insertToDatabase()
{
var db_connection = new db_connection();
string query = "UPDATE users SET facebook = 'TEST123' WHERE user_id=9";
MySqlCommand cmd = new MySqlCommand(query, db_connection.Connection);
cmd.ExecuteNonQuery();
Console.WriteLine("Command: " + query + " executed without errors.");
}
db_connection.cs file:
public class db_connection
{
/* ---- Database Variables for Connection ---- */
public MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public void Initialize(Window w)
{
string currServer = w.server.Text;
string currDatabase = w.database.Text;
string currUser = w.uid.Text;
string currPassword = w.password.Text;
server = "localhost";
database = "test";
uid = "root";
password = "test123";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
/* ---- Open connection to the database ---- */
public bool openConnection()
{
try
{
connection.Open();
Console.WriteLine("MySQL Connection opened without errors.");
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Could not establish a connection to the server.");
break;
case 1045:
Console.WriteLine("Invalid username or password");
break;
}
return false;
}
}
public MySqlConnection Connection
{
get { return this.connection; }
}
/* ---- Closing the connection to the database ---- */
public bool closeConnection()
{
try
{
connection.Close();
Console.WriteLine("MySQL Connection shutdown without errors.");
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error: " + ex.Number);
return false;
}
}
/* ---- Closing connection and trying to re-connect ---- */
public bool refreshConnection()
{
try
{
connection.Close();
Console.WriteLine("Restarting...");
connection.Open();
Console.WriteLine("Connection re-established without errors.");
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error:" + ex.Number);
return false;
}
}
I have 3 methods, called getUserID, getgazeID and updateHeatmapURL
This is getUserID
private static int getUserID()
{
int returnValue = -1;
try
{
TextReader tr = new StreamReader("C:\\Users\\L31304\\Desktop\\user.txt");
string checkedSubject = tr.ReadLine();
tr.Close();
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = checkedSubject;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue for User-" + returnValue);
return returnValue;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return returnValue;
}
}
This is getgazeID
private static int getgazeID(int userID)
{
int returnValueGaze = -1;
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "SELECT gazeID from gazeperiod WHERE userID = #userID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
returnValueGaze = (int)selectGaze.ExecuteScalar();
Console.WriteLine("returnValue for Gaze-" + returnValueGaze);
return returnValueGaze;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception for gazePeriod-" + e.ToString());
return returnValueGaze;
}
}
and this is updateheatmapURL
private static int updateHeatmapURL()
{
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "UPDATE gazeperiod(heatmapURL) VALUES (#heatmapURL) WHERE userID = #userID AND gazeID = #gazeID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = dlg.FileName;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = gazeID;
selectGaze.ExecuteScalar();
Console.WriteLine("heatmapURL - " + dlg.FileName);
}
catch (Exception e)
{
Console.WriteLine("Exception for heatmapURL-" + e.ToString());
}
}
And this is where dlg comes from.
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
dlg.Filter = "JPEG Format - jpg|*.jpg|Bitmap Format - bmp|*.bmp|Graphics Interchange Format - gif|*.gif|Portable Networks Graphic - png|*.png|Tag Image File Format - tif|*.tif|Windows MetaFile Format - wmf|*.wmf";
dlg.FileName = "*.jpg";
dlg.AddExtension = true;}
However, the userID, gazeID and dlg.FileName says:
'the name does not exist in the current context.'
How do I call it in updateURL so that it exists?
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
//dlg.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "new_folder2");
bool saveToServer = false;
//check....
if (System.IO.File.Exists("C:\\Users\\L31304\\Desktop\\user.txt"))
{
dlg.InitialDirectory = #"\\111.11.111.111\c$\Users\L31303\person\EyeTrackerWeb\WebContent\uploadheatmap";
saveToServer = true;
}
//set bool to true
//end if
dlg.Filter = "JPEG Format - jpg|*.jpg|Bitmap Format - bmp|*.bmp|Graphics Interchange Format - gif|*.gif|Portable Networks Graphic - png|*.png|Tag Image File Format - tif|*.tif|Windows MetaFile Format - wmf|*.wmf";
dlg.FileName = "*.jpg";
dlg.AddExtension = true;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
ImageFormat format;
switch (dlg.FilterIndex)
{
case 1:
format = ImageFormat.Jpeg;
break;
case 2:
format = ImageFormat.Bmp;
break;
case 3:
format = ImageFormat.Gif;
break;
case 4:
format = ImageFormat.Png;
break;
case 5:
format = ImageFormat.Tiff;
break;
case 6:
format = ImageFormat.Wmf;
break;
default:
format = ImageFormat.Jpeg;
break;
}
try
{
image.Save(dlg.FileName, format);
Console.WriteLine("file name is" + dlg.FileName);
if (saveToServer == true)
{
connectDB();
OpenConnection();
int userID = getUserID();
int gazeID = getgazeID(userID);
CloseConnection();
}
else
{
}
//if bool == true, then do the following
//select userID from user table WHERE name is name from text file
//select gazePeriodID from gazePeriod where userID the above selected userID
//update image path to gazePeriod in heatmapimage
//delete text file
}
catch (Exception ex)
{
VGExceptionMethods.HandleException(ex);
return false;
}
}
return true;
}
private static int getUserID()
{
int returnValue = -1;
try
{
TextReader tr = new StreamReader("C:\\Users\\L31304\\Desktop\\user.txt");
string checkedSubject = tr.ReadLine();
tr.Close();
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = checkedSubject;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue for User-" + returnValue);
return returnValue;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return returnValue;
}
}
private static int getgazeID(int userID)
{
int returnValueGaze = -1;
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "SELECT gazeID from gazeperiod WHERE userID = #userID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
returnValueGaze = (int)selectGaze.ExecuteScalar();
Console.WriteLine("returnValue for Gaze-" + returnValueGaze);
return returnValueGaze;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception for gazePeriod-" + e.ToString());
return returnValueGaze;
}
}
public class Form1 : Form
{
private static Form1 _instance;
public Form1()
{
this.InitializeComponent();
_instance = this;
}
private static int updateHeatmapURL()
{
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "UPDATE gazeperiod(heatmapURL) VALUES (#heatmapURL) WHERE userID = #userID AND gazeID = #gazeID";
selectGaze.CommandType = CommandType.Text;
var userID = getUserID();
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = _instance.dlg.FileName;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userID);
selectGaze.ExecuteScalar();
Console.WriteLine("heatmapURL - " + _instance.dlg.FileName);
}
catch (Exception e)
{
Console.WriteLine("Exception for heatmapURL-" + e.ToString());
}
}
}
The class is
public class Images
{
private static MySqlConnection c;
private static string server;
private static string database;
private static string uid;
private static string password;
Try this
//update these lines in updateHeatmapURL mthod
// dlg.File name is not accessable because updateHeatmapURL method is static
// use instance to access dlg or remove static, if you remove static then you need to remove it from other two methods as well
var userId = getUserID();
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userId;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userId);
EDIT
public class Form1 : Form
{
private static Form1 _instance;
public Form1()
{
InitializeComponent();
_instance = this;
}
private static int updateHeatmapURL()
{
...
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = _instance.dlg.FileName;
var userId = getUserID();
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userId;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userId);
...
}
}
I am trying to insert values in my database but unfortunately i am getting the same error again and again which i have shown in the picture(Please see the picture here: http://1.bp.blogspot.com/-oCH03jEnrdM/Uua4U9ddQZI/AAAAAAAABh0/BncJe0mHqQM/s1600/Capture.PNG) when i click the button. The error is somewhere in my Connection i think so but i am newbee therefore i dont have much idea about this error please help me in sorting out:
Here is my code:
public partial class Test : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Test()
{
InitializeComponent();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "ADC";
uid = "**********";
password = "********";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//EndDatabase
//Creating Connection
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;
case 1062:
MessageBox.Show("Duplicate Entry. Please try again with different cardentials");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//End Connection
private void Test_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var Pin = "1124";
var Sq= "What is your Name?";
var Sqa= "My Name is ";
var Bg= "B+";
var Int = "Programming";
var Skills= "Develepoment";
var webp = "xyz.com";
var addr= "DHA lahore";
var cnumber= "12324123";
string query = "INSERT INTO userprofilemoreinformation (Pin,SecurityQuestion,SecurityQuestionAnswer,BloodGroup,Interest,Skills,WebPage,Address,ContactNumber) VALUES(#Pin,#Sq,#Sqa,#Bg,#Int,#Skills,#webp,#addr,#cnumber)";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#Pin", Pin);
cmd.Parameters.AddWithValue("#Sq", Sq);
cmd.Parameters.AddWithValue("#Sqa", Sqa);
cmd.Parameters.AddWithValue("#Bg", Bg);
cmd.Parameters.AddWithValue("#Int", Int);
cmd.Parameters.AddWithValue("#Skills", Skills);
cmd.Parameters.AddWithValue("#webp", webp);
cmd.Parameters.AddWithValue("#addr", addr);
cmd.Parameters.AddWithValue("#cnumber", cnumber);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
}
It doesn't look like you ever call your Initialize method.
public Test()
{
InitializeComponent();
Initialize();
}
I have a small problem with connecting c# with a mysql database. When im trying to insert a value from a textbox i get the error below. I was wondering if someone could help me/ explain to me what im doeing wrong.
This is the error that i'm getting:
Unknown column 'test' in 'field list'
This is my code for connecting to the database:
namespace Planner
{
internal class DBConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
private string _database;
private string _uid;
private string _password;
//private string _port;
//private bool succes = false;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
string connectionString2 = "Server=localhost;Port=3307;Database=test;Uid=root;Pwd=usbw";
//+ "Port:" + _port + ";"
_server = "localhost:3307";
//_port = "3307";
_database = "test";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString2);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
private List<string>[] Select()
{
string selectquery = "SELECT * FROM tabelname";
List<string>[] selectlist = new List<string>[3];
selectlist[0] = new List<string>();
selectlist[1] = new List<string>();
selectlist[2] = new List<string>();
MySqlCommand cmd = new MySqlCommand(selectquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
selectlist[0].Add(dataReader["waarde"] + "");
selectlist[1].Add(dataReader["waarde"] + "");
selectlist[2].Add(dataReader["waarde"] + "");
}
dataReader.Close();
return selectlist;
}
public void Insert(string textvalue)
{
string insertquery = "INSERT INTO testconnectie(text) VALUES ("+textvalue+")";
MySqlCommand cmd = new MySqlCommand(insertquery, _connection);
cmd.ExecuteNonQuery();
}
private void Update()
{
string updatequery = "UPDATE tabelnaam SET waarde='', waarde'' WHERE waarde=''";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatequery;
cmd.Connection = _connection;
cmd.ExecuteNonQuery();
}
private void Delete()
{
string deletequery = "DELETE FROM tabelnaam WHERE waarde=''";
MySqlCommand cmd = new MySqlCommand(deletequery, _connection);
cmd.ExecuteNonQuery();
}
public bool CloseConnection()
{
try
{
_connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
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:\\ChatBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "Database Backup";
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! " + ex);
}
}
}
}
Mainform
namespace Planner
{
public partial class MainForm : Form
{
private DBConnect mysql = new DBConnect();
public MainForm()
{
InitializeComponent();
mysql.Initialize();
mysql.OpenConnection();
}
private void _sendMessageButton_Click(object sender, System.EventArgs e)
{
string textvalue = _messageTextBox.Text;
mysql.Insert(textvalue);
}
}
}
Can someone explain to my what im doeing wrong, thanks in advance.
you miss single quote, use like this
string insertquery = "INSERT INTO testconnectie(text) VALUES ('"+textvalue+"')";
use parameters: it is safe and you can avoid most of the exceptions like you currently get
string insertquery = "INSERT INTO YourTableName ([yourColumnName]) VALUES (#ParameterName)";
using (var con = new MySqlConnection(connectionString))
using (var cmd = new MySqlCommand(insertquery, con))
{
cmd.Parameters.AddWithValue("#ParameterName", textvalue);
con.Open();
cmd.ExecuteNonQuery();
}