C# connection with MS access is not working? - c#

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

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

Changes are not saved to the SQL Server database

The code compiles fine without error or warning, but the database does not change. I mean the changes are not saved to the database.
I wrote the following methods:
private void Test2()
{
connection = new SqlConnection();
string Conn = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
// string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(Conn);
try
{
string SQL = "UPDATE Primuser SET Following = #Following WHERE Insta = #Insta";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("#Following", "123");
sqlCommand.Parameters.AddWithValue("#Insta", "hgd");
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
and in this Code, the result is bigger than 0.
private void Test2()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Primuser";
command.Connection = connection;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset, "Primuser");
foreach (DataRow row in dataset.Tables["Primuser"].Rows)
{
if (row["Insta"].ToString() == "1495")
{
row["Following"] = "1024";
}
}
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
try
{
var result = adapter.Update(dataset, "Primuser");
if (result > 0)
MessageBox.Show("Update Successful.");
else
MessageBox.Show("Update Failed.");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
but the database does not get changed. There are no errors and other query is working. I can insert, delete or select, but update is not working.

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

Fill: SelectCommand.Connection property has not been initialized

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

I need help in query builder c#- delete doesn't work

I have a small project in c# and ms-access. I use query builder to manage my tables in ms-access.
The problem is, select query works great, update query works great, but delete doesn't work and there is no error message!
Please help.
public DataSet Update(DataSet ds)
{
using (cn)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT [taskId],[resourceId] FROM [mytable]";
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _conStrName + ";User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
adapter.SelectCommand.CommandText = queryString;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(ds.Tables["mytable";"]);
return ds;
}
public DataSet Update(DataSet ds)
{
using (cn)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT [taskId],[resourceId] FROM [mytable]";
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _conStrName + ";User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
adapter.SelectCommand.CommandText = queryString;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(ds.Tables["mytable";"]);
return ds;
}
==================================
If you are using OleDb try something like:
public static int DeleteStudentInfo(long studentNum)
{
var cmd = new OleDbCommand("DELETE FROM Students WHERE studentID = #studentId");
cmd.Parameters.Add("#studentId", OleDbType.BigInt).Value = studentNum;
return CallNonQuery(cmd);
}
private static int CallNonQuery(OleDbCommand query)
{
int rowsAffected;
var conn = new OleDbConnection(ConfigSettingsManager.DBConnectionString);
query.Connection = conn;
try
{
conn.Open();
rowsAffected = query.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
return rowsAffected;
}
Replacing ConfigSettingsManager.DBConnectionString with your connection string.
Use:
DELETE FROM Store_Information WHERE store_name = "Los Angeles"

Categories

Resources