SQL connection string for microsoft access 2010 .accdb - c#

I am doing a simple login form using winforms and access 2010 database (.accdb) in C#.
I have the following code and it seems that the connection string is wrong. I have tried searching and found that .Jet is for access 07?? but this doesnt seem to work too.
i am an amateur at databases (code referred from msdn). I am having trouble understand which should i use for this example too.
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's name is password, and the field that i want to get the value is ID.
SQL statement i wrote it as : SELECT ID FROM password
and yes, only one record in only one field in the table as the primary key.
anyway the problem is that the program hangs upon execution on the first line
-> Keyword not supported: 'provider'.
so i figured that I have a wrong connection string..

For Acces databases (.mdb, .accdb, etc...), you want to use OleDbConnection, not SqlConnection (SQL Server), like this:
conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb")

Edit: as pointed out, for access OleDbConnection should be used, not SqlConnection...
you can use a much more compact way and also be sure connection is closed and disposed in any possible case even when exceptions are thrown, by using the using statements:
your query text was also, probably wrong as others have 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 table HAHA only contains one row? Because the ExecuteScalar returns only one value, if you want to get 1 column but from many records you could use a DataReader or a DataSet...

comm.CommandText = "SELECT HAHA(*) FROM password";
It´s wrong.
"SELECT password FROM HAHA"

Your SQL statement should be,
SELECT * from HAHA
OR
SELECT [Password] From HAHA
EDIT:
You should change the ConnectionString.

Related

C# error Must declare the scalar variable

I am getting the following error and I have been doing a lot of research online to re-solve but i can't seem to find the right answer , A bit of help would be much appreciated.
Many Thanks
Error: Additional information: Must declare the scalar variable
"#Username#DepartmentName".
//DepartmentName and Username are both foreign key from LoginDetails table and Department table
SqlConnection cn = new SqlConnection(#"Data Source=PRINCENICHOLAS;Initial Catalog=Kids Company IT Asset;Integrated Security=True");
SqlCommand sqlcmdLogin = new SqlCommand("Insert into LoginDetails(Username,Password,PrivilegeCode) Values(#Username,#Password,#PrivilegeCode)", cn);
sqlcmdLogin.Parameters.AddWithValue("#Username", txtEmpFirstName.Text + '.' + txtEmpSurname.Text);
sqlcmdLogin.Parameters.AddWithValue("#Password", txtEmpPassword.Text);
sqlcmdLogin.Parameters.AddWithValue("#PrivilegeCode", cboPrivilege.SelectedItem.ToString());
cn.Open();
sqlcmdLogin.ExecuteNonQuery();
cn.Close();
//Insert Employee Table
SqlCommand sqlcmdEmp = new SqlCommand("Insert into Employee(FirstName,LastName,DOB,Email,PhoneNumber,JobRole,Username,DepartmentName) Values(#FirstName,#LastName,#DOB,#Email,#PhoneNumber,#JobRole,#Username#DepartmentName)", cn);
sqlcmdEmp.Parameters.AddWithValue("#FirstName", txtEmpFirstName.Text);
sqlcmdEmp.Parameters.AddWithValue("#LastName", txtEmpSurname.Text);
sqlcmdEmp.Parameters.AddWithValue("#DOB", dtpEmpDOB.Text);
sqlcmdEmp.Parameters.AddWithValue("#Email", txtEmpEmail.Text);
sqlcmdEmp.Parameters.AddWithValue("#PhoneNumber", txtEmpPhone.Text);
sqlcmdEmp.Parameters.AddWithValue("#JobRole", txtJobRole.Text);
sqlcmdEmp.Parameters.AddWithValue("#Username", txtEmpFirstName.Text + '.' + txtEmpSurname.Text);
sqlcmdEmp.Parameters.AddWithValue("#DepartmentName", cboDeptName.SelectedItem.ToString());
cn.Open();
sqlcmdEmp.ExecuteNonQuery();
cn.Close();​
You forget to seperate your parameter names with , like
#Username, #DepartmentName
in your sqlcmdEmp definition line.
Since you wrote it as #Username#DepartmentName, your program expect the exact name of it.
Use using statement to dispose your SqlConnection and SqlCommand instead of calling .Close() method manually.
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = cn.CreateCommand())
{
// Define your command text
// Add your paramter values
// Open your connection
// Execute your query
}
Don't store your passwords as a plain text. Read: Best way to store password in database
And don't use AddWithValue method. It may generate unexpected results sometimes. Use .Add() method or it's overloads. Read: Can we stop using AddWithValue() already?

Syntax error while trying to fetch data from MySql

So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.

Determining if user login already exists in database?

I am building a web application in asp.net using C#. I have the Form where the user should register and then can login. I am having a problem in making the web app know that the name which the user picks is either "already exists" or not. If it already exists it should not insert the same name and display a message saying "user name already exists". I have tried the SqlDataReader but no luck.
protected void Register_Button_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BJ_Player_String"].ToString());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataReader data_reader;
String name = TextBox2.Text;
String date = TextBox3.Text;
try
{
conn.Open();
cmd = new SqlCommand("Insert into BJ_Player (Player_Name, D_O_B) Values (#Player_name, #D_O_B)", conn);
cmd = new SqlCommand("Select Player_Name from BJ_Player WHERE Player_Name = #Player_name", conn);
cmd.Parameters.Add("#Player_name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("#D_O_B", SqlDbType.Date).Value = date;
cmd.Connection = conn;
data_reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
if (data_reader.HasRows)
{
lblPlayerNameExists.Visible = true;
}
else
{
// do nothing
}
}
Make Player_Name unique in database then it will give you exception when you try to insert. You have to use unique constraint.
You have to give command type also and check you assigned both queries to same cmd object
in your code you're inserting data in your DB and then you are examining that the name is the same or not.
first you should search the name in your DB and then if there isn't any record with that name ,you should add your record.
I usually do it in one of two ways:
Create stored procedure that will check for name uniqueness and insert new record if everything is ok. It should return status as numeric code that you will check.
Check for name uniqueness before saving it using as a part of validation process.
Using the merge statement may help with this. Merge performs insert, update, or delete operations on a target table based on the results of a join with a source table.
Basically it inserts when needed, and updates when needed. Often times referred to as an upsert. but it gets the job done.
Here is a link to a site explaining how to use merge. Looks like a good article.
http://www.kodyaz.com/articles/sql-server-2008-t-sql-merge-statement-example.aspx
If you would like to write a model function to do that then
Leave it for ajax check which is pretty similar to the second
method
Issue "Select username from DB-table" to retrieve
usernames then check the username input against them before
displaying a view to report a problem if any or showing a message to
tell the user that "this name is valid", for example.

Basic start with Visual Studio C# and SQL Compact (connect, select, insert)?

I'm trying to learn about C# with SQL CE so that my program can remember stuff.
I have created a database and can connect to it:
SqlCeConnection conn =
new SqlCeConnection(#"Data Source=|DataDirectory|\dbJournal.sdf");
conn.Open();
And it connects right, I guess cause if I rename the dbJournal.sdf to something wrong it doesn't debug right.
Let's say I want to make a simple SELECT query.
(SELECT * FROM tblJournal)
How is that done?
What about a simple insert?
(INSERT TO tblJournal (column1, column2, column2) VALUES
(value1, value2, value3))
I'm used to PHP and MySQL (as you properly can see :o))
#Chuck mentions EntityFramework which simplifies things and does all the work of writing the sql for you.
But there is a basic ADO.NET approach here which I will describe below.
The classes follow a standard pattern so to insert/read from sql server or other databases there are exact replica classes like SqlConnection or OleDbConnection and OleDbCommand etc
This is the most barebones ado.net approach:
using( SqlCeConnection conn =
new SqlCeConnection(#"Data Source=|DataDirectory|\dbJournal.sdf") )
using( SqlCeCommand cmd = conn.CreateCommand() )
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT * FROM tblJournal";
using( SqlCeDataReader rd = cmd.ExecuteReader() )
{
//...read
}
conn.Close();
}
Then to read data :
while (rd.Read())
{//loop through the records one by one
//0 gets the first columns data for this record
//as an INT
rd.GetInt32(0);
//gets the second column as a string
rd.GetString(1);
}
A nice and quicker way to read data is like this:
using( SqlCeDataAdapter adap =
new SqlCeDataAdapter("SELECT * FROM tblJournal", "your connection") )
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
}
This gets the entire data in one shot into a DataTable class.
To insert data :
SqlCeCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = "INSERT TO tblJournal (column1, column2, column2)
VALUES (value1, value2, value3)";
cmdInsert.ExecuteNonQuery();
If you just start learning that i will suggest you to use LINQ to make that queries.
Here is MSDN article showing features of LINQ.
http://msdn.microsoft.com/en-us/library/bb425822.aspx
Using LINQ it will be simple to do every query. For example, you can write your select query like this
from journal in TblJournal select journal
or just
context.TblJournal
also in order to improve performence , you better keep the conncection open all the time when working with SQL CE (as opposed to other standard sql databases)

No data is inserted into my table

I have a simpe table:
Users
UserID Guid doesnt allow null
Avatar image allows null
Reputation int allows null
I used the following statement:
string insertCommand = "INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
UsersIdentityToinsert(this value is a Guid, I checked its value, it isn't null).
There were no exceptions thrown. As soon as the user presses the login button, he is transfered to another page, and his record is inserted.
I followed with the debugging that that statement is executed.
When I return to my server explorer in Visual Studio 2010 and click refresh the Users table is empty. Why is that?
Connection string
<add name="YourGuruDB" connectionString="Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True"/>
i retrieve it from config into the code:
WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
Added:
public static void InsertUsers(Guid UsersIDentity)
{
SqlConnection sqlConnect = getSqlConnection();
SqlCommand sqlCommand = new SqlCommand(RegisterAdo.insertCommand(UsersIDentity), sqlConnect);//insert command method returns the insert statement described above
try
{
sqlConnect.Open();
sqlCommand.ExecuteNonQuery();
}
catch (Exception x)
{
HttpContext.Current.Response.Redirect("~/ErrorPage.aspx?Error=" + WRITE_ERROR);
}
finally
{
sqlConnect.Close();
}
}
Instead of using
"INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
use this:
"INSERT INTO Users (UserID) VALUES" +""+ "(CONVERT(uniqueidentifier, '"+UsersIdentityToinsert+"'))";
And you really should use a prepared Statement instead of concatenating the sql.
What about the DB-connection? Did you run any successfull statements so far? Try a simple select.
try this :
"INSERT INTO Users (UserID) VALUES ('"+UsersIdentityToinsert+"')";
There are a number of things to check
Are you connected to the right database?
Is the code that executes this SQL Statement actually working. You don't show that code. I'd be expecting a ExecuteNonQuery() on a SqlCommand object somewhere.
Do you actually open a connection to a database? Or is the connection string just in the config without being used anywhere in your code?
Also, your code is susceptible to a SQL Injection attack. You should use a parameterised query to prevent that. This article on SQL Injection Attacks will help you with how to write that.
You also have missing code which I'd expect to see. Something along the lines of this:
string insertCommand = "INSERT INTO Users (UserID) VALUES"
+""+ "('"+UsersIdentityToinsert+"')";
string cs = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(insertCommand, conn);
conn.Open();
cmd.ExexuteNonQuery();
conn.Close();

Categories