Issues with mysql in c# - c#

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();
}

Related

Splitting my SQL class to support multi connection and stored procedure

I need to create the best architecture for my app to manage my different connections (two) and the stored procedure.
So far I have created one SQL class and do not handle the two connections : I have mixed methods and functions which can be called regardless of the connection (and can crash).
How do I create a Connection class and a DAL ?
My SQL connection class :
namespace GripPicture.Data
{
class Sqlmap
{
static string RmSynchro = "ConnectionRmSynchro";
static string PascomPhoto = "ConnectionPascomPhoto";
private string config;
private OleDbConnection _lConnection = new OleDbConnection();
private OleDbConnection OleConnection
{
get
{
if (_lConnection.State != ConnectionState.Open)
{
if (_lConnection.State != ConnectionState.Connecting)
{
_lConnection.OpenAsync();
}
}
return _lConnection;
}
set { _lConnection = value; }
}
public Sqlmap(bool pIsPascom = false)
{
config = pIsPascom ? ConfigurationManager.AppSettings[PascomPhoto] : ConfigurationManager.AppSettings[RmSynchro];
OleConnection = new OleDbConnection(config);
}
private void Connection()
{
OleConnection.OpenAsync();
}
public int ExcuteUpdate(string pQuery)
{
// Check if connection is closed
OleDbCommand command = new OleDbCommand(pQuery, OleConnection);
return command.ExecuteNonQuery();
}
// This function should reside in your SQL-class.
public IEnumerable<T> ExecuteQueryForList<T>(string pQuery)
{
List<T> items = new List<T>();
Type type = typeof(T);
var data = ExecuteDataTable(pQuery);
foreach (DataRow row in data.Rows)
{
// Object have a constructor with a Datarow
T item = (T)Activator.CreateInstance(typeof(T), row);
PascomPhotoDo element = (PascomPhotoDo)Activator.CreateInstance(typeof(PascomPhotoDo), row);
if ((items.Cast<PascomPhotoDo>()).Any((elem => elem.NumeroContact == element.NumeroContact)))
{
LogHelper.Log("Doublons dans la liste Id Pascom " + element.NumeroContact + " " + element.FirstName + " Atlas " + element.IdParticipantAtlas);
//Console.WriteLine("Doublon dans liste : " + element.NumeroContact + " " + element.FirstName + " Atlas " + element.IdParticipantAtlas);
}
items.Add(item);
}
return items;
}
private DataTable ExecuteDataTable(string pQuery)
{
OleDbDataAdapter dp1 = new OleDbDataAdapter(pQuery, OleConnection);
DataSet ldataSet = new DataSet();
dp1.Fill(ldataSet, "table");
return ldataSet.Tables[0];
}
#region PASCOM
public byte[] GetPictureFromPascom(int pNumeroContact)
{
byte[] lDataPicture = null;
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "itsp_Photo_GetPhotoByContact";
command.Connection = OleConnection;
command.Parameters.Add("#numero_contact", OleDbType.Integer).Value = pNumeroContact;
command.CommandTimeout = 15000;
try
{
lDataPicture = (byte[])command.ExecuteScalar();
}
catch (Exception e)
{
LogHelper.Log("Fail to get picture \n" + " Id Pascom " + pNumeroContact + " " + e.Message);
}
return lDataPicture;
}
public void InsertPictureToDatabase(PascomPhotoDo pPascomPhoto)
{
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "itsp_Photo_CreatePhotoContact";
command.Connection = OleConnection;
command.Parameters.Add("#idContact", OleDbType.Integer).Value = pPascomPhoto.NumeroContact;
command.Parameters.Add("#photo", OleDbType.Binary).Value = pPascomPhoto.PhotoByteReduced;
command.Parameters.Add("#source", OleDbType.VarChar).Value = "blabla";
command.Parameters.Add("#idSalonOrganise", OleDbType.VarChar).Value = "blabla";
command.Parameters.Add("#IdParticipantAtlas", OleDbType.VarChar).Value = pPascomPhoto.IdParticipantAtlas;
command.CommandTimeout = 15000;
try
{
int data = command.ExecuteNonQuery();
}
catch (Exception e)
{
LogHelper.Log(LogTarget.File, "Fail to insert in database", e);
}
}
}
#endregion
}
Then I use my SQL connection by declaring a new object like so :
_sqlRmSynchro = new Sqlmap();
_sqlPascom = new Sqlmap(true);
As you can see I can call some specific function from the wrong connection string...
What do I need ? A DAL ? What does it look like ?

Not sure how to 'call' the variable

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);
...
}
}

MySQL C# value inserting and connection.open() is not working properly

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();
}

Issues with the c# datarow

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;
}

Can't insert a record in a oracle database using C#

try
{
int val4 = Convert.ToInt32(tbGrupa.Text);
string MyConString = "Data Source=**;User ID=******;Password=*****";
OracleConnection conexiune = new OracleConnection(MyConString);
OracleCommand comanda = new OracleCommand();
comanda.Connection = conexiune;
conexiune.Open();
comanda.Transaction = conexiune.BeginTransaction();
int id_stud = Convert.ToInt16(tbCodStud.Text);
string nume = tbNume.Text;
string prenume = tbPrenume.Text;
string initiala_tatalui = tbInitiala.Text;
string email = tbEmail.Text;
string facultate = tbFac.Text;
int grupa = Convert.ToInt16(tbGrupa.Text);
string serie = tbSeria.Text;
string forma_de_inv = tbFormaInvatamant.Text;
DateTime data_acceptare_coordonare = dateTimePicker1.Value;
DateTime data_sustinere_licenta = dateTimePicker2.Value;
string sustinere = tbSustinereLicenta.Text;
string parola_acces = tbParola.Text;
try
{
comanda.Parameters.AddWithValue("id_stud", id_stud);
comanda.Parameters.AddWithValue("nume", nume);
comanda.Parameters.AddWithValue("prenume", prenume);
comanda.Parameters.AddWithValue("initiala_tatalui", initiala_tatalui);
comanda.Parameters.AddWithValue("facultate", facultate);
comanda.Parameters.AddWithValue("email", email);
comanda.Parameters.AddWithValue("seria", serie);
comanda.Parameters.AddWithValue("grupa", grupa);
comanda.Parameters.AddWithValue("forma_de_inv", forma_de_inv);
comanda.Parameters.AddWithValue("data_acceptare_coordonare", data_acceptare_coordonare);
comanda.Parameters.AddWithValue("data_sustinere_licenta", data_sustinere_licenta);
comanda.Parameters.AddWithValue("sustinere_licenta", sustinere);
comanda.Parameters.AddWithValue("parola_acces", parola_acces);
comanda.Transaction.Commit();
MessageBox.Show("Studentul " + tbNume.Text + " " + tbPrenume.Text + " a fost adăugat în baza de date!");
}
catch (Exception er)
{
comanda.Transaction.Rollback();
MessageBox.Show("ER1.1:" + er.Message);
MessageBox.Show("ER1.2:" + er.StackTrace);
}
finally
{
conexiune.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("ER2.1:"+ex.Message);
MessageBox.Show("ER2.2:"+ex.StackTrace);
}
There doesn't seem to be an insert statement. I think this is what the problem is. You would need some thing like:
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand command = new OracleCommand(myExecuteQuery, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
There's a commit statement, what what are you going to commit if there's no insert statement prior to that?

Categories

Resources