C# database connection class not working - c#

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 :)

Related

propbem the mysqlconnection when using public variable in class level

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

C# doesn't connect to DataBase (SQL)

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

Database connection with c# using access

I want to connect to my MS Access database from c# and I am getting the following error:
unrecognized database format 'data.accdb'
What should I do? Please help
Use connection string like this:
public static string ConStr = "Provider=Microsoft.ACE.Oledb.15.0; Data Source=D:\db.accdb;";
public static void DeleteTable(string TableName)
{
OleDbConnection connection = new OleDbConnection(OLEDB.ConStr);
OleDbCommand oleDbCommand = new OleDbCommand(string.Format("delete from [{0}]", (object) TableName), connection);
try
{
connection.Open();
oleDbCommand.ExecuteNonQuery();
}
catch
{
}
finally
{
connection.Close();
}
}
I made a class for that. It works perfectly with the latest visual studio, or vs 2010 with access 2010. If you have a newer version of access you need to install the Access Database Engine. It also contains a function that strips the apostrofe preventing your sql being hacked using sql injection and a method for creating md5 hashes.
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Security.Cryptography;
public class Database
{
#region Variables
String Name;
String Path;
String ConnectionString;
OleDbConnection Connection;
#endregion
#region Init Destroy
public Database(String Name)
{
this.Name = #"App_Data\" + Name;
Path = HttpContext.Current.Server.MapPath(this.Name);
ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; " +
"Data Source = " + Path + ";" +
"Persist Security Info = False;";
Connection = new OleDbConnection(ConnectionString);
if (Connection.State == System.Data.ConnectionState.Closed)
{
Connection.Open();
}
}
public void finalize()
{
if (Connection.State == System.Data.ConnectionState.Open)
{
try { Connection.Close(); }
catch { }
}
}
#endregion
#region Queries
public void execute(String query)
{
OleDbCommand command = new OleDbCommand(query, Connection);
command.ExecuteNonQuery();
}
public OleDbDataReader select(String query)
{
OleDbCommand command = new OleDbCommand(query, Connection);
OleDbDataReader data = command.ExecuteReader();
return data;
}
public DataSet selectData(String query)
{
OleDbCommand command = new OleDbCommand(query, Connection);
OleDbDataAdapter adp = new OleDbDataAdapter(command);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
public object scalar(String query)
{
OleDbCommand command = new OleDbCommand(query, Connection);
object data = new object();
data = command.ExecuteScalar();
return data;
}
#endregion
#region Encryption Security
public String stripInjection(String field)
{
String x = field.Replace(#"'", string.Empty);
x = x.Replace(#"""", string.Empty);
return x;
}
public string md5Hash(string input)
{
StringBuilder hash = new StringBuilder();
MD5CryptoServiceProvider md5provider = new MD5CryptoServiceProvider();
byte[] bytes = md5provider.ComputeHash(new UTF8Encoding().GetBytes(input));
for (int i = 0; i < bytes.Length; i++)
{
hash.Append(bytes[i].ToString("x2"));
}
return hash.ToString().ToUpper();
}
#endregion
}
Don't put finalize instructions in the destructor of the class (As Microsoft says in the documentation because it will launch some exceptions). Just call it when you have finished your tasks:
Database database = new Database("data.accdb");
DataSet result = database.selectData("SELECT something FROM table WHERE condition;");
database.finalize();
Copy Your Databse file .accdb in Debug folder of project then add app.config file in your project
Write below code in app.config in Configuration tag
<connectionStrings>
<add name="db" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\sse_db.accdb;Persist Security Info=False;"
providerName="System.Data.Oledb" />
</connectionStrings>
1)Add System.Configuration Reference
Use connection object as follows
OleDbConnection con = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString);

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.

Fill: SelectCommand.Connection property has not been initialized

After a while using the website, loading contents, etc.. this message shows "Fill: SelectCommand.Connection property has not been initialized"!
I think this is because the sql connection, but not sure... I'd like to know what can i do to prevent this, every time this happens i have to upload a file (SQL class, that make the connection) and the website starts to work again.
My SQL connection:
public class SQL
{
SqlCommand comandos;
public SqlConnection sql()
{
string Server = #"server";
string Username = "user";
string Password = "pass";
string Database = "database";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
SqlConnection Connection = new SqlConnection();
try
{
Connection.ConnectionString = ConnectionString;
Connection.Open();
return Connection;
}
catch (Exception)
{
if (Connection != null)
{
Connection.Dispose();
}
return null;
}
}
public void FazerComando(string comando)
{
comandos = new SqlCommand(comando, sql());
comandos.ExecuteNonQuery();
}
public DataTable Execute(string comando)
{
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(comando, sql());
DataTable dtResult = new DataTable();
SQLDataAdapter.Fill(dtResult);
return dtResult;
}
}
This might be related to your problem, but in any case, it's something that should be addressed: You're not disposing your connections when you're done with them. You should use using:
public void FazerComando(string comando)
{
using (var conn = sql())
{
comandos = new SqlCommand(comando, conn);
comandos.ExecuteNonQuery();
}
}
public DataTable Execute(string comando)
{
using (var conn = sql())
{
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(comando, conn);
DataTable dtResult = new DataTable();
SQLDataAdapter.Fill(dtResult);
return dtResult;
}
}
I've never taken that approach before. We usually just use the connection string in web config, expecially with linq, it works very well. I suggest you have a look at http://blogs.msdn.com/b/visualstudio/archive/2012/06/11/world-of-samples-at-your-fingertips.aspx and follow the trail. You should find a good example of a recommended best practice for connections. The connection string will then be read at the first lauch of your app, and connection pooling (v imortant) used to best effect.
Oh and you are not disposing of your connection, which will cause a memory leek and iis to clear out your app pool when the memeory usage becomes too large -- all v bad
As the other respondant says whilst I was looking up the baet prac link...
HTH

Categories

Resources