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.
Related
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;
}
}
}
}
i want to return a string "Passed"From method Return Class Maintain, when the test passes,
And string "Failed" when the Test fails,
What I am attempting to do is make public static void Return_Pass() more dynamic and write it once instead of writing it multiple times, by passing Passed or Failed int the T-SQL statment in the method
public static void Return_Pass()
public class MainTain
{
public static void Return()
{
try
{
Thread.Sleep(5000);
Database.Return();
var icon = Browser.Driver.FindElement(By.XPath("//label[contains(text(), 'Search:')]"));
icon.SendKeys("TEST8");
Thread.Sleep(1000);
Browser.Driver.FindElement(By.XPath("//button[#title='Edit user']")).Click();
Thread.Sleep(500);
Browser.Driver.FindElement(By.XPath("//button[.= 'Return']")).Click();
Thread.Sleep(500);
Maint_Tests_Pass.Return_Pass();
Console.WriteLine(P);
}
catch (Exception e)
{
Browser.Closed();
Maint_Tests_Fail.Return_Fail();
Environment.Exit(-1);
}
}
}
To method Return_Pass Class Maint_Tests_pass
public class Maint_Tests_Pass
{
public static void Return_Pass()
{
string connetionString;
SqlConnection cnn;
connetionString = "Server=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\marco zani\\Documents\\marco.mdf\";Integrated Security=True;Connect Timeout=30";
cnn = new SqlConnection(connetionString);
SqlCommand command;
string sql = "INSERT INTO TestRun (Date,Message) VALUES (GETDATE(),'Test Return Passed')";
command = new SqlCommand(sql, cnn);
cnn.Open();
command.ExecuteReader();
cnn.Close();
cnn.Dispose();
}
}
i am fairly new to C# any help is appreciated..
method return_pass now
public static void Return_Pass(bool pass, string test)
{
string connetionString;
SqlConnection cnn;
connetionString = "Server=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\marco zani\\Documents\\marco.mdf\";Integrated Security=True;Connect Timeout=30";
cnn = new SqlConnection(connetionString);
SqlCommand command;
string passValue = pass ? "Passed" : "Failed";
string testreturn = test;
string sql = $"INSERT INTO TestRun (Date,Message) VALUES (GETDATE(),'{test} {passValue}')";
//string sql = "INSERT INTO TestRun (Date,Message) VALUES (GETDATE(),'Test Return Passed')";
command = new SqlCommand(sql, cnn);
cnn.Open();
command.ExecuteReader();
cnn.Close();
cnn.Dispose();
}
return method now
public static void Return()
{
try
{
Thread.Sleep(5000);
Database.Return();
var icon = Browser.Driver.FindElement(By.XPath("//label[contains(text(), 'Search:')]"));
icon.SendKeys("TEST8");
Thread.Sleep(1000);
Browser.Driver.FindElement(By.XPath("//button[#title='Edit user']")).Click();
Thread.Sleep(500);
Browser.Driver.FindElement(By.XPath("//button[.= 'Return']")).Click();
Thread.Sleep(500);
Maint_Tests_Pass.Return_Pass(true,"Test Return");
}
catch (Exception e)
{
Browser.Closed();
Maint_Tests_Pass.Return_Pass(false, "Test Return");
Environment.Exit(-1);
}
}
Rather than having two separate functions, have one that takes a boolean and inserts the appropriate record.
public static void Record(bool passed)
{
string connetionString;
SqlConnection cnn;
connetionString = "Server=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\marco zani\\Documents\\marco.mdf\";Integrated Security=True;Connect Timeout=30";
cnn = new SqlConnection(connetionString);
SqlCommand command;
string sql = $"INSERT INTO TestRun (Date,Message) VALUES (GETDATE(),'Test Return {(passed ? "Passed" : "Failed"}')";
command = new SqlCommand(sql, cnn);
cnn.Open();
command.ExecuteReader();
cnn.Close();
cnn.Dispose();
}
And call thusly:
try
{
// as before
Maint_Tests_Pass.Record(true);
}
catch(Exception ex)
{
Maint_Tests_Pass.Record(false);
}
Now, it's beyond the scope of both your question and this answer, but when you've got this working, how about looking at parameterised SQL queries:
https://www.completecsharptutorial.com/ado-net/insert-records-using-simple-and-parameterized-query-c-sql.php
Have fun!
use string instead of void
then return your value
public static string Return_Pass()
{
...
return "yourvalue";
}
Based on my understanding of the question
public static void Return_Pass(bool pass)
{
// ...
// ...
string passValue = pass ? "Passed" : "Failed";
string sql = $"INSERT INTO TestRun (Date,Message) VALUES (GETDATE(),'Test Return {passValue}')";
// ...
// ...
}
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();
... ...
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 :)
When I add a Car in my application I get
The ConnectionString property has not been initialized.
I have the problem of ConnectionString property. I check similar question of mine but I found nothing helpfulness.
I use a class connection named dbConnection.cs:
class dbConnection
{
//Connection to database
private string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE".ToString();
public string Con
{
get
{
return con;
}
}
}
This is the code of my button
private void btnAddCar_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtCar = new DataTable();
BindingSource Car_bs = new BindingSource();
using (SqlCommand cmd = new SqlCommand("sp_Add_Car", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
//......
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtCar.Clear();
da.Fill(dtCar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
refreshCar();
}
This is the code of an another button working well without error
private void btnAddPayment_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtPayment = new DataTable();
using (SqlCommand cmd = new SqlCommand("sp_Add_Paiements", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id_paiement", SqlDbType.Char).Value = txtBoxPaymentId.Text;
cmd.Parameters.Add("#montant", SqlDbType.SmallMoney).Value = txtBoxAmount.Text;
cmd.Parameters.Add("#id_Location", SqlDbType.Char).Value = cmbpaymentLesaseId.Text;
//cmd.Parameters.Add("#status", SqlDbType.Char).Value = txtBoxStatusPayment.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtPayment.Clear();
da.Fill(dtPayment);
btnAddLease.Hide();
refreshPayments();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
btnAddPayment.Hide();
}
You aren't showing where you have initialized your dbConnection class. Changing it all to static will probably help, I'm guessing:
static class dbConnection
{
//Connection to database
private static string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE"
public static string Con
{
get
{
return con;
}
}
}
If your dbConnection class worked in one method but not the other, chances are you had it initialized in one and not the other. Unless you have to deal with different database connections, using a static class for your database connections is probably the best route.
Then you change your calling method like this:
using (SqlConnection con = new SqlConnection(dbConnection.Con))
{
// blah-blah
}
Assuming dc is your connection, then it has to be initialized with a connection string. Maybe - if it's a class - you have to set some properties, like database path, etc.
SqlConnection Con= New SQLConnection(#"Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE");