How do I enter information into an Access Database through C#? - c#

I'm developing the username/password creation system for my program. It's just going to be used in a computing lab, and I'm just going to have a central Access database that distributes through scripts on the lab machines. Or that's the plan right now. I can't remember the proper code to insert the info into the database to save my life though. This is what I've got so far. The hashing and salting seem to be going fine, I just can't shove it into the database. The name of the table is regulate.
I'm getting "number of query fields and destination fields are not the same".
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=access.mdb";
conn.Open();
string Name = txtName.Text;
string PW = txtHash.Text;
string Salt = txtSalt.Text;
OleDbCommand cmmd = new OleDbCommand("INSERT INTO regulate(regulate) Values(#NAME, #PASSWORD, #SALT)", conn);
if (conn.State == ConnectionState.Open)
{
cmmd.Parameters.Add("#NAME", OleDbType.VarWChar, 100).Value = Name;
cmmd.Parameters.Add("#PASSWORD", OleDbType.VarWChar, 500).Value = PW;
cmmd.Parameters.Add("#SALT", OleDbType.VarWChar, 10).Value = Salt;
try
{
cmmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException expe)
{
MessageBox.Show(expe.Message);
conn.Close();

The OleDbCommand uses a different format for parameters than SqlCommand, as you see in the documentation:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
And as #codenheim suggests, check the syntax of your INSERT command.
Also, PASSWORD is a reserved word in Jet SQL, so you probably need to quote that column name. I believe either these quote styles would work:
INSERT INTO regulate(name, `password`, salt) Values(?, ?, ?)
INSERT INTO regulate(name, [password], salt) Values(?, ?, ?)

The number of fields and types in this:
INSERT INTO regulate(regulate)
must match this:
Values(var1, var2, var3)
Should be something like:
INSERT INTO regulate(name, password, salt) Values(?, ?, ?)
assuming these are the column names.
PS: I don't use OleDb very often, but I believe you need ? instead of named #arg per #p.s.w.g's answer. (Upvote his/her answer if this helps). I can confirm all of my OleDb code does indeed use positional arguments only.

First important thing is to make sure that your path to your access.mdb is correct.
Then also make sure that if your supplying 3 parameters to your insert statement (in your case, the #NAME, #PASSWORD, #SALT), you must also have a matching column each for those 3 parameters to assign to.
string cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=access.mdb";
OleDbConnection c = new OleDbConnection(cs);
string Name = txtName.Text;
string PW = txtHash.Text;
string Salt = txtSalt.Text;
try
{
c.Open();
string s = "INSERT INTO regulate(NAME, PASSWORD, SALT) Values (#NAME, #PASSWORD, #SALT)";
using (OleDbCommand cmd = new OleDbCommand(s, c))
{
cmd.Parameters.AddWithValue("#NAME", Name);
cmd.Parameters.AddWithValue("#PASSWORD", PW);
cmd.Parameters.AddWithValue("#SALT", Salt);
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}

Related

How to store ImagePath in Mysql Database?

I am trying to store an image path in my mysql database but it does not store the backslash(/).
this is my path - string str = #"C:\Users\user\Downloads\99 Most Amazing Collection of Computer Desktop Wallpapers - 5522 [ECLiPSE]"
this is how it appears in mysql - C:UsersuserDownloads99 Most Amazing Collection of Computer Desktop Wallpapers - 5522 [ECLiPSE]
Because of this i am unable to retrive the image, so how do i store the imagepath with the backslash included.
Mysql Code
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
string str = #"C:\Users\user\Downloads\99 Most Amazing Collection of
Computer Desktop Wallpapers - 5522 [ECLiPSE]"
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogimagestable (ImagesId)values('" + str + "');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
You should use parametrized queries to prevent such problems from happen automatically. And other nasty things, like SQL injections.
And you should rather call ExecuteNonQuery() instead of ExecuteReader() for a statement, that doesn't return a result. Or at least take care of calling Dispose() on the useless reader or using using. (Same goes for your other disposable objects.)
...
string Query = "INSERT INTO test.blogimagestable (ImagesId)values(?str);";
MySqlCommand cmd = new MySqlCommand(Query, conn)
cmd.Parameters.Add("?str", MySqlDbType.VarString, 256).Value = str;
cmd.ExecuteNonQuery();
...
Change the type and length passed to Parameters.Add() according to the type of your column.

Why I'm getting Incorrect syntax near ')' error?

I'm trying to create a registration page using C# on Visual Basic 2012. When I debug I get 0 errors, but when I try to register an account I get the following error.
"Incorrect syntax near ')'"
If I try to create an account with an existing username it says that username already exist. So I'm able to connect to the SQL server, but I'm not sure where I went wrong.
This registration page should create accounts in my DB DNMembership> Table> Accounts
Here is my code I'm working with.
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString);
con.Open();
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#AccountName", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Passphrase", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
What did I do wrong?
Looks like you forget to add VALUES part in your INSERT command.
VALUES
Introduces the list or lists of data values to be inserted. There must
be one data value for each column in column_list, if specified, or in
the table. The value list must be enclosed in parentheses.
Change your sql query like;
string insCmd = #"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES(#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)";
And use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString))
{
using(SqlCommand insertUser = new...)
{
//Your code..
}
}
You haven't specified any parameters in your SQL, or a VALUES section - you're saying "I want to insert into these fields..." but not what you want to insert. It should be something like:
string insCmd =
"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) "
+ "Values (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country");
You need to change the SQL statement:
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) VALUES (#AccountName,#Passphrase,#EmailAddress,#FullName,#Country)";
You are missing part of Insert statement
INSERT INTO table (col1, col2) VALUES (#col1, #col2)
Or if you want to insert all values into columns in order they are in table
INSERT INTO table VALUES (#col1, #col2)
There is several alternatives for INSERT command in SQL Server.
Specify COLUMNS and after that specify VALUES
SQL Syntax - INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
If you are sure about the order of columns you can skip specifying columns, this can be risky in case you screw up order of VALUES you will insert values into wrong columns
SQL Sytanx - INSERT INTO TABLE VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
Good resources to read would be
W3School - http://www.w3schools.com/sql/sql_insert.asp
Technet - http://technet.microsoft.com/en-us/library/dd776381(v=sql.105).aspx
Alternative to INSERT INTO TABLE you can call stored procedures from C# that inserts into table. Use of stored procedures can help you reduce ad-hoc queries, help prevent SQL injection, reduce network traffic, add additional validation server side. Your code will look as follows.
SqlCommand cmd = new SqlCommand("usp_InsertIntoAccount", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#AccountName", TextBoxUN.Text));
cmd.Parameters.Add(new SqlParameter("#Passphrase", TextBoxPass.Text));
cmd.Parameters.Add(new SqlParameter("#EmailAddress", TextBoxEA.Text));
cmd.Parameters.Add(new SqlParameter("#FullName", TextBoxFN.Text));
cmd.Parameters.Add(new SqlParameter("#Country", DropDownListCountry.SelectedItem.ToString()));
try
{
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
Additional resources are listed on answer at the following questions How to execute a stored procedure within C# program

why data is not saving to database?

I have tried the following code to save to a database. The condition is are, I have a value in a dropdown list and the values are New= 1, and old=2. If the user selects 1 or new then it will save data to database or if they select old then it will show the exist data.
Now this time my label shows data inserted but the data is not saved to the table (But doesn't show any error).
protected void btnsave_Click(object sender, EventArgs e)
{
if (ddl.Text=="1")
{
cs.Open();
string query = "insert into resig (#id,#name,#email) values('"+txtgn.Text+"','"+txtgname.Text+"','"+txtsg.Text+"')";
SqlCommand cmd = new SqlCommand(query,cs);
lbdmsg.Text = "Data Inserted";
//txtgname.Text = ddl.SelectedItem.ToString();
}
else
{
cs.Open();
string query = "select name, email from resig where id='" + txtgn + "'";
SqlCommand cmd= new SqlCommand(query,cs);
dr =cmd.ExecuteReader();
while(dr.Read())
{
string name= txtgname.Text;
string email=txtsg.Text;
}
cs.Close();
}
}
I see 2 things;
You are try to parameterize your column names, not your values.
You are not executing your insert command with ExecuteNonQuery().
You should use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
if (ddl.Text == "1")
{
string query = "insert into resig (id,name,email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query,cs);
cmd.Parameters.AddWithValue("#id", txtgn.Text);
cmd.Parameters.AddWithValue("#name", txtgname.Text);
cmd.Parameters.AddWithValue("#email", txtsg.Text);
cs.Open();
cmd.ExecuteNonQuery();
}
Call cmd.ExecuteNonQuery() to run the command on your db
Your SQL is both wrong, and very dangerous/susceptible to SQL injection. The first list in parenthesis must be a column list, and the values list should be parameters to avoid SQL injection:
string query = "insert into resig (id, name, email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query, cs);
cmd.Parameters.Add(new SqlParameter("#id", txtgn.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtgname.Text));
cmd.Parameters.Add(new SqlParameter("#email", txtsg.Text));
cmd.ExecuteNonQuery();
You should parameterize the select statement as well. Why is this important? Consider the resulting SQL if the user entered this for id and selected old:
'; delete resig; --
Building SQL by concatenating user input opens your database to the whim of users with bad intentions, and in this day and age should never be used. Countless web sites have been defaced and had their data corrupted -- it was ill-considered back in the day, but now we know better, and there's no excuse.

Insert into database table with OLE DB .NET Provider won't work

I am getting an error msg of "syntax error" for the INSERT INTO command when it gets to cmd.ExecuteNonQuery.
It is important that I use string.Format, and that the structure stays as close to the current structure as possible.
{
OleDbConnection con = DAL.GetConnection();
con.Open();
if (con.State == ConnectionState.Open)
{
string s = string.Format("INSERT INTO DataTable1 (Username, Password, FName, LName, Bdate, Sex, City, Mail) VALUES ('{0}', '{1}', '{2}', '{3}', #{4}#, {5}, {6}, '{7}')", uname, pass, fname, lname, bd, sex, city, mail);
OleDbCommand cmd = DAL.GetCommand(con, s);
int check = cmd.ExecuteNonQuery();
if (check == 0)
{
con.Close();
Response.Redirect("Reg.aspx?err=-An error has occured. Please try again-");
}
Thank you.
Probably you have some quotes in the passed text, try using parameters ...
string s = "INSERT INTO DataTable1 (Username) VALUES (#user)";
OleDbCommand cmd = DAL.GetCommand(con, s);
//Add the parameter ...
OleDbParameter nam = new OleDbParameter("#user",uname);
cmd.Parameters.Add(nam);
Check out OleDbCommand.Parameters if you haven't already. It is safer (along the lines of #Mark B's comment), and it will probably clear up the syntax error you have.
If you insist on a pure String.Format approach, simply output cmd.CommandText for debugging to see where the syntax error lies.

issues using parameter queries

I'm trying to switch come of my SQL queries to parameter queries but i keep getting some errors shown after the code below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (#Surname,[#Other Names],#mobileno,#date, #email, #faculty, #dept, [#Registration Number], #session,#thesis, #yearGrad, #tellerno, #amount, #address,#question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("#Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("#[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("#mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("#date", lblDate.Text);
cmd.Parameters.AddWithValue("#email", lblEmail.Text);
cmd.Parameters.AddWithValue("#faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("#dept", lblDept.Text);
cmd.Parameters.AddWithValue("#[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("#session", lblSession.Text);
cmd.Parameters.AddWithValue("#thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("#yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("#tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("#amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#address", lblAdd.Text);
cmd.Parameters.AddWithValue("#question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
Error message is:
Server Error in '/TranscriptReloaded' Application.
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#date".
"date" is a SQL reserved word, so the translation to SQL may be having a problem with it. Generally speaking you should avoid using the word date on its own as column names or as parameters.
Personally I would start by losing the #[two word] variable names (which you also use as [#two word] elsewhere). I don't know if this is the cause, but I have never seen this usage personally, and I'm dubious. Fine for column names (and table names), but variables? Not so sure. Changing the variable names is local to this code, so shouldn't cause any side-effects.

Categories