I am trying to connect to the SQL Server database in C#, and check that the database contains an empty table with 3 columns, but I don't know how to check if it is successful or not..
My code:
protected bool checkDB()
{
string ConnectionString = "Server=[serverName];Database=[databaseName];Trusted_Connection=true";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand("SELECT * FROM tableName", con);
// use the connection here
con.Open();
con.Close();
if (success)
{
return true;
}
else
{
return false;
}
}
protected bool checkDB()
{
var connString = #"Server=myServerName\myInstanceName;Database=myDataBase;Integrated Security=true;";
try
{
using (var con = new SqlConnection(connString))
{
con.Open();
using (var com = new SqlCommand("SELECT * FROM tableName", con))
{
// use your query here...
}
}
return true;
}
catch (Exception)
{
return false;
}
}
Related
I'm getting this error on phpMyAdmin
mysqli_connect(): (08004/1040): Too many connections
The only script that is using this DB:
public static bool checkIp(string ip)
{
Console.WriteLine("CHECKIP");
try
{
string sql = " SELECT * FROM `Ip tables` ";
MySqlConnection con = new MySqlConnection("host=hostname;user=username;password=password;database=database;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
con.Close();
return false;
}
catch(SqlException exp)
{
throw new InvalidOperationException("Error", exp);
}
}
Does this code close the connection correctly or something is wrong?
EDIT:
I added this block after the catch block
finally
{
if(con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
Any better way to write the code? Would finaly block still run if return is executed?
You should put your query in a using statement like this:
string conString= "host=hostname;user=username;password=password;database=database;"
using (MySqlConnection con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM `Ip tables`";
using (MySqlDataReader dr = com.ExecuteReader())
{
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
}
}
}
This will automatically close the connection without having to state con.Close()
I have a code that I use to login.
I call the data I get from textbox with a method and check the records with select query in the
database.
I call to relevant method , when I press the button.
private void btnGiris_Click(object sender, EventArgs e)
{
LoginBilgiler lb = new LoginBilgiler();
bool sonuc = lb.GirisKontrol(txtAd.Text, txtSifre.Text);
}
But I encounter errors in cmd.ExecuteReader the below.
public bool GirisKontrol(string ad,string sifre)
{
using (OracleConnection con = new OracleConnection(connectionString))
{
string query = String.Format("SELECT count(*) from Z_LABEL_USER where USERNAME=({0}) and PASSWORD=({1})", ad,sifre);
OracleCommand cmd = new OracleCommand(query, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
kAdi = ad;
con.Close();
return true;
}
else
con.Close();
return false;
}
}
The table I use for the select query.
Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01722: invalid
number'
Please, don't hardcode parameters in SQL; parametrize it instead:
public bool GirisKontrol(string ad, string sifre) {
//DONE: validate public methods' input
if (string.IsNullOrEmpty(ad))
return false; // or throw exception
else if (string.IsNullOrEmpty(sifre))
return false; // or throw exception
using (OracleConnection con = new OracleConnection(connectionString)) {
con.Open();
//DONE: no need to count all the entires, just check if there's at least one
//DONE: keep query readable
//DONE: paramterize queries
string query =
#"select 1
from Z_LABEL_USER
where USERNAME = :prm_UserName
and PASSWORD = :prm_Password";
using (OracleCommand cmd = new OracleCommand(query, con)) {
//TODO: this syntax can vary from library to library you use to work with Oracle
cmd.Parameters.Add(":prm_UserName", OracleType.VarChar).Value = ad;
cmd.Parameters.Add(":prm_Password", OracleType.VarChar).Value = sifre;
using (OracleDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
//TODO: Side effect : it changes instance's state. Do you really want it?
kAdi = ad;
return true;
}
}
}
}
return false;
}
I have just finished making a contact application, where basically you input the contacts details and it will save it to a SQL database.
I am very sorry if my code is confusing everyone because I am a big noobie at coding.
Connection String
<add name="connstrng" connectionString="Data Source=DESKTOP-MJ61J7L\SQLEXPRESS;Initial Catalog=Econtact;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
C#
class contactClass
{
//getter and setter properties
//acts as data carrier in our application
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ContactNo { get; set; }
public string Address { get; set; }
public string Gender { get; set; }
static string myconnstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
//selecting data from database
public DataTable Select() {
//Database Connection
SqlConnection conn = new SqlConnection(myconnstrng);
DataTable dt = new DataTable();
try
{
//Writing sql query
string sql = "SELECT * FROM tbl_contact";
//creating cmd using sql and conn
SqlCommand cmd = new SqlCommand(sql, conn);
//creating sql dataAdapter using cmd
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
adapter.Fill(dt);
} catch(Exception e)
{
} finally
{
conn.Close();
}
return dt;
}
//inserting data into DataBase
public bool Insert (contactClass c)
{
//creating a default return type and setting its value to false
bool isSuccess = false;
//Connect to DataBase
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_contact (FirstName, LastName, ContactNo, Address, Gender) VALUES (#FirstName, #LastName, #ContactNo, #Address, #Gender) ";
//creating cmd using sql and conn
SqlCommand cmd = new SqlCommand(sql, conn);
//Inserting Parameters into tbl_contact
cmd.Parameters.AddWithValue("#FirstName", c.FirstName);
cmd.Parameters.AddWithValue("#LastName", c.LastName);
cmd.Parameters.AddWithValue("#ContactNo", c.ContactNo);
cmd.Parameters.AddWithValue("#Addresss", c.Address);
cmd.Parameters.AddWithValue("#Gender", c.Gender);
conn.Open();
int row = cmd.ExecuteNonQuery();
//if the query runs successfully then the value of the rows will be != 0 (because the default it 0)
if(row > 0)
{
isSuccess = true;
} else
{
isSuccess = false;
}
} catch(Exception e)
{
} finally
{
conn.Close();
}
return isSuccess;
}
//method to update data in our database from our application
public bool Update(contactClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "UPDATE tbl_contact SET FirstName=#FirstName, LastName=#LastName, ContactNo=#ContactNo, Address=#Address, Gender=#Gender WHERE ContactID=#ContactID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#FirstName", c.FirstName);
cmd.Parameters.AddWithValue("#LastName", c.LastName);
cmd.Parameters.AddWithValue("#ContactNo", c.ContactNo);
cmd.Parameters.AddWithValue("#Addresss", c.Address);
cmd.Parameters.AddWithValue("#Gender", c.Gender);
//open database connection
conn.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception e)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
//method to delete data from our database
public static bool Delete(contactClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
//sql to delete data
string sql = "DELETE FROM tbl_contact WHERE ContactID=#ContactID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ContactID", c.ContactID);
//open sql connection
conn.Open();
int rows = cmd.ExecuteNonQuery();
//runs the isSuccess variable if statement
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch(Exception e)
{
}
finally
{
//Close sql connection
conn.Close();
}
return isSuccess;
}
}
Add Button
private void btnAdd_Click(object sender, EventArgs e)
{
//Get the value from the input fields
c.FirstName = txtboxFirstName.Text;
c.LastName = txtboxLastName.Text;
c.ContactNo = txtboxPhonenumber.Text;
c.Address = txtboxAddress.Text;
c.Gender = cmbGender.Text;
c.FirstName = txtboxFirstName.Text;
//inserting data into the database using the method we created in the last video
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("New contact successfully created.");
}
else
{
MessageBox.Show("Failed to add contact. Try Agian.");
}
}
I do think that it might be due to the connection to my data base....
I Also got this message in my output-
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Idk if this means anything though.
#mjwills Addresss is misspelled (twice). That would explain what you are seeing.
Thanks man, uhgg so obvious. I really appreciate it I would never have found that.
Why am I getting this error:
Connection state has not been intialized
when I'm using one method in other?
This is my DbConnectio.cs:
public class DbContext
{
public SqlConnection sqlconn = null;
public SqlConnection DbConnection
{
get { return sqlconn; }
set { value = sqlconn; }
}
public DbContext()
{
string cs = ConfigurationManager.ConnectionStrings["CTXDB"].ConnectionString;
sqlconn = new SqlConnection(cs);
}
}
web.config:
<add name="CTXDB"
connectionString="Data Source=Md;Initial Catalog=Md;User ID=sa;Password=123;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
This is my Repo.cs - here I'm implementing my business logic:
DbContext db = new DbContext();
public Employee FindEmpById(int key)
{
SqlConnection conn = db.DbConnection;
try
{
var employee = new Employee();
if (conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand("Sp_GetEmployeeById", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", key);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows == true)
{
while (rdr.Read())
{
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.EmpName = rdr["EmpName"].ToString();
employee.Email = rdr["Email"].ToString();
employee.Psw = rdr["Psw"].ToString();
}
}
return employee;
}
catch (Exception)
{
throw;
}
finally
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
}
}
}
This FindEmpById I call in DeleteEmpById function
public void DeleteEmpById(int Key)
{
SqlConnection Con = db.DbConnection;
var x = FindEmpById(Key);
if (x != null)
{
if (Con.State != ConnectionState.Open)
{
Con.Open();
}
SqlCommand cmd = new SqlCommand("sp_DeleteById", Con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", Key);
cmd.ExecuteNonQuery();
}
}
FindEmpById disposes the connection conn.Dispose();. So, when you try to use it afterwards, it is not valid any more.
Don't try to reuse a connection. Create a new connection each time you need one. Internally the physical connections are pooled automatically, i.e., the same physical connection will be reused when possible. Creating a new connection with new SqlConnection is lightweight.
Instead of doing
SqlConnection conn = db.DbConnection; // WRONG!
// All your try catch finally and testing for conn.State --- WRONG!
do
// OK!
using (SqlConnection conn = db.CreateConnection()) {
conn.Open();
...
} // Automatically closed and disposed here.
Where CreateConnection creates a new SqlConnection at each call. This is also much easier and straight forward. Change your DbContext class to
public class DbContext
{
private static readonly string _connectionString;
static DbContext()
{
_connectionString = ConfigurationManager.ConnectionStrings["CTXDB"].ConnectionString;
}
public SqlConnection CreateConnection()
{
return new SqlConnection(_connectionString);
}
}
Your overhauled FindEmpById method becomes
public Employee FindEmpById(int key)
{
using (SqlConnection conn = db.CreateConnection())
using (SqlCommand cmd = new SqlCommand("Sp_GetEmployeeById", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", key);
var employee = new Employee();
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader()) {
if (rdr.Read()) {
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.EmpName = rdr["EmpName"].ToString();
employee.Email = rdr["Email"].ToString();
employee.Psw = rdr["Psw"].ToString();
}
}
return employee;
}
}
Btw: You don't need to call FindEmpById(Key) before deleting. Just delete. It is not an error to delete 0 records in SQL.
public void DeleteEmpById(int Key)
{
using (SqlConnection conn = db.CreateConnection())
using (SqlCommand cmd = new SqlCommand("sp_DeleteById", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", Key);
conn.Open();
cmd.ExecuteNonQuery();
}
}
I am using the below code to access the MS Access Database. But i got a error message Fill: SelectCommand.Connection property has not been initialized.How can i solve this issue.
common.cs
=========
public static bool DBConnectionStatus()
{
try
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_admin.mdb; Jet OLEDB:Database Password=admin";
using (OleDbConnection conn = new OleDbConnection(conString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
}
catch (OleDbException)
{
return false;
}
protected void btn_general_Click(object sender, EventArgs e)
{
try
{
bool state = common.DBConnectionStatus();
if (state == true)
{
cmd = new OleDbCommand("select * from tbl_admin");
da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds); // Error Here
if (ds.Tables[0].Rows.Count > 0)
{
}
}
}
catch (Exception e1)
{
}
}
I did suggest you to modify your code to something like this:
private DataTable YourData()
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_admin.mdb; Jet OLEDB:Database Password=admin";
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(conString))
{
try
{
conn.Open();
SqlCommand command = new SqlCommand("select * from tbl_admin", conn);
command.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
// do somethign here
}
}
catch (Exception)
{
/*Handle error*/
}
}
return ds.Tables[0];
}
And then:
protected void btn_general_Click(object sender, EventArgs e)
{
this.YourData(); // you will get the Data here. you can then use it the way you want it
}
You are initializing a Command which you use to construct a DataAdapter, but both without setting the required Connection property:
cmd = new OleDbCommand("select * from tbl_admin"); // <-- no connectuion assigned
da = new OleDbDataAdapter(cmd); // <-- no connectuion assigned
So your exception is pretty self-explanatory.
One final note: using will dispose/close the connection, so the method DBConnectionStatus is pointless. So don't use it, instead use the using in in the first place:
try
{
using(var con = new OleDbConnection(connectionString))
using(var da = new OleDbDataAdapter("elect * from tbl_admin", con))
{
var table = new DataTable();
da.Fill(table); // note that you don't need to open the connection with DataAdapter.Fill
if (table.Rows.Count > 0)
{
// ...
}
}
}
catch (Exception e1)
{
// don't catch an exception if you don't handle it in a useful way(at least loggging)
throw;
}
As per your requirement you can also use SqlDataAdapter instand of ExecuteReader.
public void ReadMyData(string connectionString)
{
string queryString = "SELECT OrderID, CustomerID FROM Orders";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetString(1));
}
// always call Close when done reading.
reader.Close();
}
}