C# Form Application - Saving Data to access database - c#

As a group we are working on a project and need to save the data collected in the label in a field in an access database. However we have been having some troubles with this function.
Here is the code what i have tried so far:
We changed the values from lbl.View.text to "1" for testing purposes, but still no luck.
private void complete_btn_Click(object sender, EventArgs e)
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = connStr;
OleDbCommand cmd = con.CreateCommand();
// error is in insert statement somehwhere.
cmd.CommandText = "INSERT INTO Users (TimeStamp, Interest, TotalTime)" + "VALUES('" + "1" +"', '"+ "1" + "','" + "1" + "');";
// conn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True");
// cmd = new OleDbCommand("", con);
// cmd.Parameters.AddWithValue("#TimeStamp", lblView.Text);
// cmd.Parameters.AddWithValue("#Interest", lblView.Text);
// cmd.Parameters.AddWithValue("#TotalTime", lblView.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}

Based on your exception message, TimeStamp is a reserved keyword in MS Access. You need to use it with square brackets like [TimeStamp]. As a better way, change it to non-reserved word which is meaningful for your column.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO Users (TimeStamp, Interest, TotalTime)
VALUES(?, ?, ?)";
cmd.Parameter.AddwithValue("#p1", "1");
cmd.Parameter.AddwithValue("#p2", "1");
cmd.Parameter.AddwithValue("#p3", "1");
con.Open();
cmd.ExecuteNonQuery();
}

Related

Syntax error in UPDATE statement while updating password in Access database

I faced syntax error in UPDATE statement, while updating password in Access database in C#:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE into userdata(password)values('"+TextBox1.Text+"') where id=#id";
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
}
It's because your SQL Query is not correct, that's not how you update data in your database. It should be like this:
query = "Update [tableName] SET [ColumnName] = 'Values', [ColumnName1] = 'Values2',...";
You should learn at least the basics of SQL syntax, more information here
And also, you shouldn't concatenate your query since it will become vulnerable for SQL Injection attack, you should at least use Parameterized Query
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE yourTableName SET [yourColumnName] = #YourFirstValue, [secondColumnName] = #YourSecondValue WHERE [columnKey] = #ID"
cmd.Parameters.AddWithValue("#YourFirstValues", textbox1.Text);
cmd.Parameters.AddWithValue("#YourSecondValue ", textbox2.Text);
cmd.Parameters.AddWithValue("#ID", textbox3.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
you have to fix your query
"UPDATE userdata SET password=#password where id=#id";
and add new lines before cmd.ExecuteNonQuery()
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
I had a similar problem, it gave me a syntax error that I solved by checking the whole string and actually there was a comma too many, I don't know if this answer of mine can be useful, among other things after some time.

How to insert data into a database table using a SqlCommand

I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.

multiple queries on 1 button click

I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();

How to create exception for database file not found in c#

I have to connect my code to the access database but mainly, have to provide clear exception if that database file is not located in given location (like file not found). For this code :
string connStr =( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";
conn1.Open();
cmd.ExecuteNonQuery();
I want to display message if test database is not present there. What can I do ? please suggest. thank you
I think you can use the static method File.Exists:
if(!File.Exists("Z:\\test.accdb"))
throw new FileNotFoundException();
try
{
string connStr =( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";
conn1.Open();
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
//print the message you want;
}

Using parameters inserting data into access database

I have the following method to inserting data into an an access databasewhich works fine but I do get a problem if I try to insert text that contains single quotes I have learned.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES('" + title + "', '" + rating + "','" + review + "','" + ISBN + "', '" + userName + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
From what I understand one of the ways to solve the problem is by using parameters. I am not sure how to do this to be honest. How could I change the above code so that I insert the data by using parameters instead?
Same as for any other query:
a) Replace actual hardcoded parameters in your OleDbCommand with placeholders (prefixed with #),
b) Add instances of OleDbParameter to the DbCommand.Parameters property. Parameter names must match placeholder names.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
using (OleDbConnection conn = new OleDbConnection(
"Provider=Microsoft.Jet.OleDb.4.0;"+
"Data Source="+Server.MapPath("App_Data\\BookRateInitial.mdb"));
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
// create command with placeholders
cmd.CommandText =
"INSERT INTO bookRated "+
"([title], [rating], [review], [frnISBN], [frnUserName]) "+
"VALUES(#title, #rating, #review, #isbn, #username)";
// add named parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#title", title),
new OleDbParameter("#rating", rating),
...
});
// execute
cmd.ExecuteNonQuery();
}
}
}
You have to use Parameter to insert Values. Its is allso a security Issue.
If you do it like that a sql injection could by made.
Try like this:
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
For Microsoft Access the parameters are positional based and not named, you should use ? as the placeholder symbol although the code would work if you used name parameters provided they are in the same order.
See the documentation for OleDbCommand.Parameters Property
Remarks
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. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
Be sure to include the expected schema type where the parameter will be used AND the schema length if applicable.
I also recommend you always use using statements around your instances where the type implements IDisposable like the OleDbConnection so that the connection is always closed even if an exception is thrown in the code.
Changed Code:
var connectionStringHere = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb";
using (var conn = new OleDbConnection(connectionStringHere))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO bookRated ([title], [rating], [review], [frnISBN], [frnUserName]) VALUES(?, ?, ?, ?, ?)";
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) { Value = title});
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.Integer) { Value = rating });
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 2000) { Value = review });
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 60) { Value = ISBN });
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 256) { Value = userName });
conn.Open();
var numberOfRowsInserted = cmd.ExecuteNonQuery();
}

Categories