Database connection with c# using access - c#

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

Related

The first data line skip

I wrote code to connect to the NETEZZA database. When a response is received, the first line of the result disappears, i.e. only 9 of 10 lines are displayed. I read that there are such problems with the OLEDB driver, but I could not resolve the issue myself.
I tried to add the parameter HDR = YES
class SQL_zapros
{
private string connString = "Provider=NZOLEDB;Password=PASSWORD; User ID=LOGIN; Data Source=127.0.0.1; Initial Catalog=SYSTEM; Persist Security Info=True;";
public string sqlcomm = "";
public DataTable exeReader(string cmd, OleDbParameter[] param)
{
OleDbConnection oConn = new OleDbConnection(connString);
OleDbCommand oCmd;
OleDbDataReader oReader;
DataTable AppData = new DataTable();
oConn.Open();
oCmd = oConn.CreateCommand();
oCmd.CommandText = cmd;
try
{
oReader = oCmd.ExecuteReader();
if (oReader.Read())
{
AppData.Load(oReader);
oReader.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
oConn.Close();
return AppData;
}
}
I want to get all the rows from the database
oReader.Read() reads the first line of the result. AppData.Load also does that, the first line of the result is ignored. To fix it remove the if block, just pass the reader directly.
Also use using blocks when creating instances where the type implements IDisposable. This ensures the resources are always released even in the event of an exception.
public DataTable exeReader(string cmd, OleDbParameter[] param)
{
using(OleDbConnection oConn = new OleDbConnection(connString))
{
DataTable AppData = new DataTable();
oConn.Open();
var oCmd = oConn.CreateCommand();
oCmd.CommandText = cmd;
try
{
using(var oReader = oCmd.ExecuteReader()) {
AppData.Load(oReader);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
return AppData;
}
I would recommend to use OleDbDataAdapter instead. Try like:
...
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(cmd, oConn);
adapter.Fill(AppData);
...

how to build a SQL connection using C# in Visual Studio 2017?

I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET

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

Multi users safe SQL Connection

I have an object below:
public class DatabaseAccess
{
private static string sConnStr;
private static SqlConnection sqlConn;
private static string ConnectionString
{
get
{
if (String.IsNullOrEmpty(sConnStr))
{
sConnStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
return sConnStr;
}
}
public static int OpenConnection
{
get
{
sqlConn = new SqlConnection(ConnectionString);
return 0;
}
}
public static SqlConnection Connection
{
get
{
if (sqlConn.State != ConnectionState.Open)
{
sqlConn = new SqlConnection(ConnectionString);
sqlConn.Open();
}
return sqlConn;
}
}
}
So whenever I need a connection in my web application, I use something like:
DataTable dt = new DataTable();
using (SqlConnection cnn = DatabaseAccess.Connection)
{
using (SqlDataAdapter da = new SqlDataAdapter("MyAStoredProcedure", cnn))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
}
}
return dt;
It all seems well except when there are 2 users running the codes at the same time, I will get in my web application the following error:
There is already an open DataReader associated with this Command needs to be Closed.
I need some advice how do I resolve the above issue?
Thank you.
That's because you're sharing connection objects - don't do that. DatabaseAccess.Connection should create a new SqlConnection every time.
Try to create a new instance of SqlConnection in the using statement
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
cnn.Open();
using (SqlDataAdapter da = new SqlDataAdapter("MyAStoredProcedure", cnn))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
}
}
return dt;

Would authentication settings on SQL server 2008 R2 make any performance difference?

Alright this is the first method
public static string srConnectionString = "server=localhost;database=myDB; "+
" uid=sa;pwd=myPW;";
And this is the second method
public static string srConnectionString = "server=localhost;database=myDB; "+
" integrated security=SSPI;persist security info=False; Trusted_Connection=Yes;";
Are there any performance difference or any other difference between these 2 connection strings?
Here my sql connection class any suggestion ?
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class DbConnection
{
public static string srConnectionString = "server=localhost; database=myDB; uid=sa; pwd=myPW;";
public static DataSet db_Select_Query(string strQuery)
{
DataSet dSet = new DataSet();
if (strQuery.Length < 5)
return dSet;
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection))
{
DA.Fill(dSet);
}
}
return dSet;
}
catch
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1)
{
connection.Open();
strQuery = strQuery.Replace("'", "''");
using (SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection))
{
command.ExecuteNonQuery();
}
}
}
return dSet;
}
}
public static void db_Update_Delete_Query(string strQuery)
{
if (strQuery.Length < 5)
return;
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.ExecuteNonQuery();
}
}
}
catch
{
strQuery = strQuery.Replace("'", "''");
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection))
{
command.ExecuteNonQuery();
}
}
}
}
}
The performance difference is insignificantly small that it can be ignored. The authentication checks are
...performed only on login. The connection is not rechecked for each query. However with connection pooling, the connection is authenticated and reset many times, quite possibly for nearly every query
...the same as every file access and other activity involving the domain getting checked against Active Directory
FYI these two settings are the same (use one or the other):
integrated security=SSPI
Trusted_Connection=Yes

Categories

Resources