I have a database to manage a school (students and classes).
I have a class with the code to connect to the DataBase and then I call the functions in the main program.
When I try to interact with the DataBase, it warns me that it could not connect to the DataBase or it exceeded the connection time.
I tried to add an ssslmode but it didn't work. I also tried to add a port but it didn't work.
Code for the class:
public class ligacao
{
public MySqlConnection connection;
string server;
public string data_base;
string user_id;
string password;
public void inicializa()
{
server = "localhost";
data_base = "escola";
user_id = "root";
password = "usbw";
string connection_string;
string sslmode = "none";
connection_string = "SERVER=" + server + ";" + "DATABASE=" + data_base + ";" + "UID=" + user_id + "PASSWORD=" + password + ";" + "SslMode=" + sslmode + ";";
connection = new MySqlConnection(connection_string);
}
public bool open_connection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0: MessageBox.Show("Couldn't connect t DataBase."); break; // couldn't connect to database
case 1042: MessageBox.Show("Exceded the connection time"); break; // exceeded the connection time
case 1045: MessageBox.Show("Username/password are incorrect"); break;
}
return false;
}
}
public bool close_connection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
Code for the Main Program:
public partial class consultas : Form
{
ligacao x = new ligacao();
public consultas()
{
InitializeComponent();
x.inicializa();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void consultas_Load(object sender, EventArgs e)
{
//define query
string query = "SELECT designacao FROM disciplinas";
//open connection
if (x.open_connection())
{
//create the comand and associates the query with the connection through the connector
MySqlCommand cmd = new MySqlCommand(query, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["designacao"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
//define query
string queryBI = "SELECT bi FROM alunos";
//open connection
if (x.open_connection())
{
//create the commando and associate the query with the connection through the constructor
MySqlCommand cmd = new MySqlCommand(queryBI, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["bi"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
}
}
I think there is something wrong with your connection string. Try using the MySqlConnectionStringBuilder:
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Host = "localhost";
builder.UserId = "root";
builder.Database = "escola";
builder.Password = "usbw";
connection = new MySqlConnection(builder.ConnectionString);
Try This :
connection_string = #"Data Source = " + server + "; Initial Catalog = " + data_base + "; Integrated Security=True;uid=myUser;password=myPass;";
Related
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
I tried connecting a very simple program in C# and save it to database but I always get the exception error which is "System.InvalidOperationException: 'The connection is already open.'"
Here's my code:
namespace sample
{
public partial class Form1 : Form
{
public MySqlConnection connection;
public Form1()
{ InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{ DBConnect dbc = new DBConnect();
dbc.Insert();
}
}
I tried closing the connection when the form start and non to avail.
and for the MySQL class in which I think where the error is:
class DBConnect
{ private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{ Initialize(); }
private void Initialize()
{ server = "localhost";
database = "csample";
uid = "root";
password = "1234";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString); }
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;
} MessageBox.Show("Failed!"); return false; }
}
private bool CloseConnection() {
try
{ connection.Close();
return true; }
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false; }
}
public void Insert()
{
string query = "INSERT INTO info values ('cedie','taguig'); ";
if (this.OpenConnection() == true)
{ MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("CONNECTION OPENED \n SUCCESS!"); }
else if (this.OpenConnection() == false) {
MessageBox.Show("CONNECTION CLOSED \n FAILED!");
}}}}
Don't mind the labels and textboxes as this program is just to execute the mysql
I am creating an app whose first window is a database configuration window. From this window, a user inputs server details and selects the database they want to use upon which the database connection details and carried over to the login window and the window is opened.
The login and subsequent windows use the database details for their sql connection string.
My question here is this: how can I save these connection details from the configuration window such that the user bypasses this screen if they have already established a previous connection? I have the idea to store these details to a file and set a boolean condition in App.xaml.cs, but I do not know how to go about doing it.
Here is my code:
For the Database Settings Window
DatabaseSettings.xaml.cs
private void btnTest_Click(object sender, RoutedEventArgs e)
{
try
{
connectionString = "Data Source = " + txtServer.Text + "; User Id = " + txtUserID.Text + "; Password = " + txtPassword.Password + "";
conn = new SqlConnection(connectionString);
conn.Open();
string message = "Connection Successful Please Select a Database to Proceed";
string caption = "Success!";
MessageBoxButton buttons = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Information;
System.Windows.MessageBox.Show(message, caption, buttons, icon);
txtServer.IsEnabled = false;
txtUserID.IsEnabled = false;
txtPassword.IsEnabled = false;
btnTest.IsEnabled = false;
cmbdatabase.IsEnabled = true;
btnConfigure.IsEnabled = true;
btnConfigure.IsDefault = true;
sql = "EXEC sp_databases";
command = new SqlCommand(sql, conn);
reader = command.ExecuteReader();
cmbdatabase.Items.Clear();
while (reader.Read())
{
cmbdatabase.Items.Add(reader[0].ToString());
}
conn.Close();
}
catch(Exception ex)
{
System.Windows.MessageBox.Show("Error: " + ex);
}
}
static string Encrypt_Password(string value)
{
using (SHA256Managed sha2 = new SHA256Managed())
{
UTF8Encoding uTF8 = new UTF8Encoding();
byte[] data = sha2.ComputeHash(uTF8.GetBytes(value));
return Convert.ToBase64String(data);
}
}
private void btnConfigure_Click(object sender, RoutedEventArgs e)
{
try
{
string selected = cmbdatabase.Text;
txtSelectedDBItem.Text = cmbdatabase.Text;
string EncryptedPassword = Encrypt_Password(txtPassword.Password);
connectionString = "Data Source = " + txtServer.Text + "; Initial Catalog = " + selected + "; User Id = " + txtUserID.Text + "; Password = " + txtPassword.Password + "";
conn = new SqlConnection(connectionString);
sql = "INSERT INTO Proc_Activity_Log ([UserName], [Password], [AccessTime], [MachineSerial]) values(#userId, #password, #accessTime, #machineserial)";
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#userID", txtUserID.Text);
cmd.Parameters.AddWithValue("#password", EncryptedPassword);
cmd.Parameters.AddWithValue("#accessTime", dateTime.Text);
cmd.Parameters.AddWithValue("#machineserial", txtMachineSerialNo.Text);
cmd.ExecuteNonQuery();
}
UserInterface.frmLogin loginScreen = new UserInterface.frmLogin(txtUserID.Text, txtPassword.Password, txtServer.Text, txtSelectedDBItem.Text);
spashScreen.Show();
this.Close();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error Here:" + ex.Message);
}
}
For the login screen
frmLogin.xaml.cs
public frmLogin(string uname, string pwd, string server, string db)
{
InitializeComponent();
txtServerUser.Text = uname;
txtServerPwd.Password = pwd;
txtServer.Text = server;
txtSelectedDBItem.Text = db;
}
private void btnOk_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=" + txtServer.Text + "; Initial Catalog=" + txtSelectedDBItem.Text + "; Integrated Security=True;");
try
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
String query = "SELECT COUNT(1) FROM dbo.users WHERE name=#Username and password=#Password";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", txtLogin.Text);
sqlCmd.Parameters.AddWithValue("#Password", txtPwd.Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
frmMDI yourDesktop = new frmMDI(txtLogin.Text, txtServerUser.Text, txtServerPwd.Password, txtServer.Text, txtSelectedDBItem.Text);
yourDesktop.Show();
this.Close();
}
else
{
txtLogin.Text = "admin";
txtPwd.Password = "admin";
txtLogin.Focus();
}
}
catch (Exception ex)
{
string message = "The Following Error Occurred: " + ex.Message;
string caption = "Invalid Action";
MessageBoxButton buttons = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Error;
System.Windows.MessageBox.Show(message, caption, buttons, icon);
}
finally
{
sqlCon.Close();
}
}
From the screenshots I have included below one can infer which buttons represent the click events in the code above
Database Settings Window - Testing Connection
Database Settings Window - Testing Connection
Database Settings Window - Configuring Database
Database Settings Window - Configuring Database
And finally the login window
login window
Im following a C# database connection tutorial however the code they provide for the connection class has a problem, it has an error on dat_set which I'm assuming needs to be set as a variable but I'm unsure. Having looked at the code the tutorial provides many times what i have is exactly the same
The errors are these lines
da_1.Fill(dat_set, "Table_Data_1");
return dat_set;
Here is what i have
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
namespace JBT
{
class DBConnect
{
private string sqlString;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
public string Sql
{
set { sqlString = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get
{ return MyDataSet(); }
}
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sqlString, con);
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
}
}
The Dataset that you want to Fill need to be intialized before
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sqlString, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
Of course this could work only if you have initialized the sqlString and the strCon before calling this code. This should be assumed because you say that the error occurs at the Fill line
The
System.Data.DataSet MyDataSet() is not what you have to put in your code if you are using Mysql
first initialize the code.
then write methods to open and close connection.
now you are ready for the db connection.
public class DbConnection
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
private void initialize()
{
server = "localhost";
database = "yourdatabase";
uid = "root";
password = "";
string connectionString = "server=" + server + ";database=" + database + ";uid=" + uid + ";password=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open 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;
}
return false;
}
}
if you want to develop complete db connection use this site: http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
helped me a lot :)
I have an issue connecting to an oracle database from my test server. Bellow is my code snippet.
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
private static string GetConnectionString()
{
String connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=IP_Address)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=Service_Name)));User Id=hook;Password=Password;";
return connString;
}
private string ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
try
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = " select * from sgmp.web_portal1 where account_no= '" + customerIdField.Value.ToString().Trim() + "'";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Session["ClientName"] = (string)reader["Customer_Name"];
return (string)reader["Customer_Name"];
}
}
else
{
resp.Text = "Client ID '" + customerIdField.Value.ToString().Trim() + "' does not exist in records";
return "none";
}
return "none";
}
catch (OracleException ex)
{
resp.Text = ex.Message + " reasons ..";
return "mmm";
}
}
I got nothing as exception and I can't just connect.
Regards.
My first with Oracle after-all.
I found the solution here: http://support.microsoft.com/kb/255084 All I needed to do was step 1 to 5