SQL connection string to access Microsoft 2010.accdb

I am making a simple login form using winforms and accessing a 2010 database (.accdb) in C #.

I have the following code and it seems that the connection string is incorrect. I tried to find and found that .Jet to access 07 ?? but this does not seem to work. I am an amateur in databases (code from msdn). I am having trouble understanding what I should use for this example.

access table name: haha

  ID (PK) |  password
 -----------------------
    1 |  testing
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb"); System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(); comm.CommandText = "SELECT HAHA(*) FROM password"; comm.CommandType = CommandType.Text; comm.Connection = conn; conn.Open(); Object returnValue = comm.ExecuteScalar(); conn.Close(); MessageBox.Show((string)returnValue); 

edited: the table name is the password, and the field I want to get is the identifier.

The SQL statement I wrote it as: SELECT ID FROM password

and yes, only one entry in only one field in the table as a primary key.

In any case, the problem is that the program freezes when executed on the first line
-> Keyword not supported: 'provider'.

so I realized that I have the wrong connection string.

+6
source share
4 answers

For Acces databases (.mdb, .accdb, etc.) you want to use OleDbConnection rather than SqlConnection (SQL Server), e.g.

 conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb") 
+7
source

Edit : as indicated, OleDbConnection should be used to access, not SqlConnection ...

you can use a much more compact way, and also make sure that the connection is closed and located in any possible case, even if exceptions are thrown, using using statements:

your query text was also probably incorrect as others suggested ...

 using (var conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb")) using (var comm = conn.CreateCommand()) { comm.CommandText = "SELECT password FROM HAHA"; comm.CommandType = CommandType.Text; conn.Open(); var returnValue = comm.ExecuteScalar(); MessageBox.Show(returnValue.ToString()); } 

Edit: Are you sure the HAHA table contains only one row? Since ExecuteScalar returns only one value, if you want to get 1 column, but from many records you can use DataReader or DataSet ...

+2
source
 comm.CommandText = "SELECT HAHA(*) FROM password"; 

It is not right.

"SELECT password FROM HAHA"

0
source

Your SQL statement should be,

 SELECT * from HAHA 

OR

  SELECT [Password] From HAHA 

EDIT:

You must change ConnectionString .

0
source

Source: https://habr.com/ru/post/899278/


All Articles