propbem the mysqlconnection when using public variable in class level - c#

I have c# class that make me to connect the database and make some operations on it.
#region Var
private readonly string DbPath;
public MySqlConnection DbConn;
#endregion
#region Constructor
public ClsDb()
{
DbPath = "SERVER= " + Db.Default.ServerName + "; " +
"DATABASE= " + Db.Default.DbName + "; " +
"UID= " + Db.Default.UserName + "; " +
"PWD= " + Db.Default.UserPass + "; " +
"PORT= " + Db.Default.ThePort+"; sslmode=none";
DbConn = new MySqlConnection(DbPath);
}
#endregion
as you see I declared (mysqlconnection) :
DbConn = new MySqlConnection(DbPath);
so after that I check the connection:
public bool CheckConn()
{
try
{
if (DbConn.State == ConnectionState.Open)
{
DbConn.Close();
}
if (DbConn.State == ConnectionState.Closed)
{
DbConn.Open();
return true;
}
return false;
}
catch
{
MessageBox.Show(Msgs.Default.ConnErr,
Settings.Default.ComName,
MessageBoxButtons.OK,
MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
return false;
}
}
and after that I'm trying to execute SQL statement by method:
public void RunSql(string xSql, MySqlParameter[] xPar)
{
//...
MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
// ....
if (xPar != null)
{
xCmd.Parameters.AddRange(xPar);
}
//...
xCmd.ExecuteNonQuery();
}
but it gives me the following error:
"Connection must be valid and open."
when I checked the code by the breakpoints I got that everything is ok and it opens the connection very well but when it execute (public void RunSql) and exactly on the line:
MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
when I tried to solve it I changed (public MySqlConnection DbConn) to (public Static MySqlConnection DbConn) and it worked but I needed to know why that happened although I declared the variable as public?? and why it worked when I changed to Static??

I'm using my own class for this. In it isn't necessary to close the connection because uses the 'using'.
The class:
Connection (return open connection)
public static MySqlConnection GetConn()
{
MySqlConnection conn = new MySqlConnection(ConnString);
try
{
conn.Open();
}
catch (MySqlException)
{
throw;
}
return conn;
}
Insert Commands (accept params)
public static int InsertSqlCommand(string db, params (string param, object value)[] listParams)
{
using (MySqlConnection conn = GetConn())
{
using (MySqlCommand cmd = new MySqlCommand(db, conn))
{
foreach ((string dbLocal, object incremento) in listParams)
cmd.Parameters.AddWithValue(dbLocal, incremento);
int linhasAfetadas = cmd.ExecuteNonQuery();
return linhasAfetadas;
}
}
}
Select Command (accept params)
public static DataTable SelectSqlCommand(string db, params (string param, object value)[] listParams)
{
DataTable dttoken = new DataTable();
using (MySqlConnection conn = GetConn())
{
using (MySqlCommand cmd = new MySqlCommand(db, conn))
{
foreach ((string dbLocal, object incremento) in listParams)
cmd.Parameters.AddWithValue(dbLocal, incremento);
using (MySqlDataAdapter sqlDA = new MySqlDataAdapter(cmd))
{
sqlDA.Fill(dttoken);
return dttoken;
}
}
}
}

Related

Insert Data into database via mySQL using visual studio in C#

So I'm trying to insert data into an SQL Database, which was created in Visual Studio 2017 via a Service-Based Database.
Here is the code
private void save() {
Book book = new Book();
book.Id = System.Convert.ToInt32(idtxtbox.Text);
book.title = titletxtbox.Text;
book.author = authortxtbox.Text;
string query = "INSERT INTO Book VALUES(" + System.Convert.ToInt32(idtxtbox.Text) + "," + titletxtbox.Text + "," + authortxtbox.Text + ")";
using (conn = new SqlConnection(connString))
using (SqlCommand command = new SqlCommand(query, conn)) {
conn.Open();
command.ExecuteNonQuery();// Error here
conn.Close();
}
clear();
}
If I enter data like
id = 001
title = "The Book"
Author = "Main Author"
I get an error that says " System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Book'.' ". What am I doing wrong, and how can I fix it?
Try to do it this way and thus avoid sql injections:
SqlConnection conexion;
private void save() {
conexion = cConexion.getConexion();
SqlCommand comand = new SqlCommand();
comand.Connection = conexion;
comand.CommandText = "INSERT INTO Book(Id, title, author) VALUES(#Id, #title, #author)";
comand.Parameters.Add("Id", SqlDbType.Int, 3).Value = this.idtxtbox.Text;
comand.Parameters.Add("title", SqlDbType.NChar).Value = this.titletxtbox.Text;
comand.Parameters.Add("author", SqlDbType.NChar).Value = this.authortxtbox.Text;
comand.ExecuteNonQuery();
clear();
}
I like to use a connection class to handle the connections
class cConexion
{
private static SqlConnection conexion;
public static SqlConnection getConexion()
{
if (conexion != null)
{
return conexion;
}
conexion = new SqlConnection(Properties.Settings.Default.MyConnectionString);
try
{
conexion.Open();
return conexion;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error" + e.Message);
return null;
}
}
public static void cerrarConexion()
{
if (conexion != null)
{
conexion.Close();
}
}
}

Error Connecting to Database in VB

I'm working on a login function in visual studio, I have my code listed below to connect to the database. I can't figure out what I'm doing wrong here, but I get the error databaseConn.db_connection() is a method which is not valid in the given context.
using MySql.Data.MySqlClient;
namespace Connection
{
static class databaseConn
{
static public void db_connection()
{
try
{
var conn = "Server=myhomeserver.net;Database=addonInstaller;Uid=root;Pwd=g278535814;";
var connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
MessageBox.Show("Could not Connect to Server");
}
}
}
}
namespace UserFunctions
{
static class Users
{
static public void LoginFunc(String username, String password)
{
CheckUsername(username, password);
}
static public void CheckUsername(String username, String password)
{
Connection.databaseConn.db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM users WHERE username=" + username + "";
cmd.Connection = Connection.databaseConn.db_connection.Open(); //This is my error area.
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
MessageBox.Show("Continue to Login");
}
else
{
MessageBox.Show("Username Not Found");
}
}
}
}
You have define the db_connection as a static function, not a property, so that you can't use db_connection.Open().
You can try to modify your db_connection to return the connection object, or store it as static property
databaseConn:
static public MySqlConnection db_connection()
{
try
{
var conn = "Server=myhomeserver.net;Database=addonInstaller;Uid=root;Pwd=g278535814;";
var connect = new MySqlConnection(conn);
connect.Open();
return connect;
}
catch (MySqlException e)
{
MessageBox.Show("Could not Connect to Server");
}
return null;
}
Users:
var conn = Connection.databaseConn.db_connection();
if (conn != null)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM users WHERE username=" + username + "";
cmd.Connection = conn;
MySqlDataReader login = cmd.ExecuteReader();
... ...

Cannot implicity convert type error

Trying to fill Combobox with data from a database and I'm using ExecuteReader as below, but when I try to instantiate my connection it shows me the error
Cannot implicitly convert type error
My DBConnect class code:
public class DBConnect
{
private SqlConnection connection;
private string servername = "10.1.76.109,1433";
private string database = "EngLib";
private string dbuser;
private string userpassword;
public DBConnect()
{
}
public void doDBConnect(string dbuserform, string userpasswordform)
{
dbuser = dbuserform;
userpassword = userpasswordform;
}
public void Initialize()
{
}
public bool openConnection()
{
string connectionString;
connectionString = "Server=" + servername + ";Database=" + database + ";user id=" + dbuser + ";Password=" + userpassword;
Console.WriteLine(connectionString);
connection = new SqlConnection(connectionString);
try
{
connection.Open();
return true;
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Não é possível contactar o servidor. Entre em contato com o administrador");
break;
case 18456:
MessageBox.Show("Usuário/Senha inválidos, tente novamente");
break;
}
return false;
}
}
My form code:
{
public Form2()
{
InitializeComponent();
}
public void Form2_Load(object sender, EventArgs e)
{
SqlDataReader rdr = null;
DBConnect sqlConnection;
sqlConnection = new DBConnect();
sqlConnection.doDBConnect(dbuserform: "usertest", userpasswordform: "usertest");
{
try
{
{
sqlConnection.openConnection();
SqlCommand sqlCmd;
sqlCmd = new SqlCommand("SELECT Material FROM EngLib");
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
comboBox1.Items.Add(sqlReader["Material"].ToString());
}
sqlReader.Close();
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
}
}
}
}
The user and password in the code is just temporary.
I think the problem is here:
DBConnect sqlConnection;
SqlCommand sqlCmd;
sqlCmd.Connection = sqlConnection;
SqlCommand expects that Connection is of type SqlConnection, but you are assigning your own class DBConnect.
Possible fixes:
Expose the connection property on DBConnect and use it.
Inherit DBConnect from SqlConnection.
Use SqlConnection directly.
An additional note: you are not disposing the SqlConnection inside your DBConnect class, which can lead to StackOverflowException. You should implement IDisposable.

C# connection with MS access is not working?

When I start debugging and I add some clients, I can add them, update them and read them. But the newly added clients won't save in my database. I've checked if I'm using the right file location and I am:
public class DBaccess
{
private static string connectionstr;
static DBaccess()
{
string mdffile;
mdffile = #"C:\Users\rik\Documents\Visual Studio 2010\Projects\Week-2-Opdracht\Database\Clienten.accdb";
connectionstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mdffile + ";";
}
public static DataSet Getwaardenquery(string sqlstr)
{
DataSet ds = new DataSet();
Console.WriteLine(sqlstr);
OleDbConnection con = new OleDbConnection(connectionstr);
OleDbDataAdapter dap = new OleDbDataAdapter(sqlstr, con);
dap.Fill(ds);
return ds;
}
public static int Uitvoerenquery(string sqlstr)
{
int resultaat = -1;
Console.WriteLine(sqlstr);
OleDbConnection con = new OleDbConnection(connectionstr);
OleDbCommand cmd = new OleDbCommand(sqlstr, con);
try
{
con.Open();
resultaat = cmd.ExecuteNonQuery();
}
catch (Exception exp)
{
string x = exp.Message;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
return resultaat;
}
}
}
At first check your connection string is correct or not by making a manual connection.
For help follow the given link
http://www.c-sharpcorner.com/UploadFile/b8d90a/connect-oledb-database-in-C-Sharp-in-easy-steps/
your code contain extra semicolon
connectionstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + mdffile + "'";
syntax error

Provider & query

I want to create a C # application that can create and populate a DataTable.
Here is my code:
public DataTable GetData(string query)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
using (DbConnection conn = factory.CreateConnection())
{
try
{
DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();
csb["Data Source"] = #"";
csb["User Id"] = #"";
csb["Password"] = #"";
conn.ConnectionString = csb.ConnectionString;
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
using (DataTable dt = new DataTable())
{
DbDataAdapter da = factory.CreateDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
catch (Exception ex)
{
throw new Exception("Error", ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
In a second time, I have a class containing my various queries.
public class Query
{
public string SQL;
public string query1()
{
this.SQL = "select * from table1"
return this.SQL;
}
public string query2(string param)
{
this.SQL = "select * from table1 where id = '" + param + "' ";
return this.SQL;
}
I wish I could go query1 and / or query2 as parameter of my method GetData.
public DataTable GetData(query1)
{
//...
}
But I do not know how!
Thank you in advance for your help!

Categories

Resources