Connecting to Access database - c#

I'm trying to connect to database file "crepeDB.accdb"
When I added it through data connection, and works fine when I drag any table to appear as data grid in any form but when I try to connect to the database to insert data it gives me this error:
An unhandled exception of type 'System.NotImplementedException' occurred in Additional information: The method or operation is not implemented.
The code I'm using is as follows:
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;");
conn.Open();
string query = "insert into Sales (Sdate,SQuantity) values ('" + dateTimePicker1.Value + "','" + textBox9.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
This is the last thing I need to do in my project, would really appreciate any help.

Do not pass values for your fields concatenating them to form your command, instead use parameters.
int quantity;
if(!Int32.TryParse(textBox9.Text, out quantity))
MessageBox.Show("Invalid number");
else
{
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"insert into Sales (Sdate,SQuantity)
values (#date, #qta)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("#date", OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#qta", OleDbType.Integer).Value = quantity;
cmd.ExecuteNonQuery();
}
}
This is better because you don't ask someone else to convert your values from a string to the correct datatype. This automatic conversion (in particular with dates) is well know to cause problems when there is some kind of mismatch between the passed string and how the database engine interprets this string
N.B I am assuming the Sdate is a field of type DateTime and SQuantity is a field of type Integer in MS-Access. If not then you can change the OleDbType Int32.TryParse to the correct matching type

It is basically like this . . .
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();

Related

What is the correct way of using (INSERT SELECT FROM WHERE) query in C#?

I'm making a form on C# that inserts data in a table with a where clause, but it's not working. I think the syntax of my query is the problem but I can't solve it.
This is the one that I tried that's working, but I need an insert query with a where clause.
SqlCommand addEmp = new SqlCommand("INSERT INTO tbl_Expenses " +
"(InvestedMoney,EstimatedServingCount,MealName) " +
"VALUES (#inv, #est, #mname)", conn);
addEmp.Parameters.AddWithValue("#mname", textBox1.Text);
addEmp.Parameters.AddWithValue("#inv", textBox2.Text);
addEmp.Parameters.AddWithValue("#est", textBox3.Text);
conn.Open();
addEmp.ExecuteNonQuery();
conn.Close();
I tried this code below:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Meal" +
" ExpensesID, MealName, MealPrice, ImageName, Imageblob)" +
"SELECT ExpensesID, #mname, #mprice, #imname, #img " +
"FROM tbl_Expenses" +
"WHERE MealName = '"+textBox1.Text+"'",conn);
cmd.Parameters.AddWithValue("#mname", textBox1.Text);
cmd.Parameters.AddWithValue("#mprice", textBox4.Text);
cmd.Parameters.AddWithValue("#imname", textBox1.Text);
cmd.Parameters.Add("#img", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
But I get this error:
System.Data.SqlClient.SqlException: Incorrect syntax near '='
This section is missing a space between the lines:
"from tbl_Expenses" +
"WHERE MealName = '"
so the sql code references a table named tbl_ExpensesWHERE, gives the table an alias of MealName, and then has an out-of-place =.
But you should also already know from the use of parameters elsewhere it is NOT okay to substitute textBox1.Text into the query like that. NEVER do that. Not even once. Not even for practice/learning code!
There are some other poor practices in here, but that was the worst. Here's a better pattern:
string sql = #"
INSERT into tbl_Meal
(ExpensesID,MealName,MealPrice,ImageName,Imageblob)
SELECT
ExpensesID,#mname,#mprice,#mname,#img
FROM tbl_Expenses
WHERE MealName = #mname";
using (var conn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, conn))
{
//wild guess at column types. Use actual column types/size FROM THE DATABASE
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 30).Value = textBox1.Text;
cmd.Parameters.Add("#mprice", SQlDbType.Decimal, 18, 8).Value = textBox4.Text;
//use the size of the column here, not the length of the photo
cmd.Parameters.Add("#img", SqlDbType.Image, 8000).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
}
Instead of Parameters.AddWithValue() use Parameters.Add() and also use correct datatypes, for example EstimatedServingCount seems to be an int, but however AddWithValue can not know that:
addEmp.Parameters.Add("#mname", SqlDbType.VarChar).Value = textBox1.Text;
addEmp.Parameters.Add("#inv", SqlDbType.VarChar).Value = textBox2.Text;
addEmp.Parameters.Add("#est", SqlDbType.Int).Value = textBox3.Text;

DateTime error type mismatch

I'm trying to insert date and time to my access db using c#, this is what i currently have, but it says mismatch
OleDbConnection myConn = new OleDbConnection();
myConn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Copro-3\Employee.accdb;Persist Security Info=False;";
myConn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConn;
cmd.CommandText = #"insert into EmployeeTimeIn (FirstName,LastName, TimeIn) values ('"+textBox1.Text+"', '"+textBox2.Text+"' , ?)";
cmd.Parameters.AddWithValue("TimeIn", DateTime.Now);
cmd.ExecuteNonQuery();
MessageBox.Show("Success");
myConn.Close();
I'm trying to insert date and time to my access db using c#, this is what i currently have, but it says "data type mismatch"
Type of TimeIn in ms access table is different than you pass TimeIn value as parameter

Execute Datetime from C# to date in SQL Server 2008

I'm new in programming and want you to help me.
I have field of type (date) and when I insert data to database from my website in visual studio 2010 with C#, it Shows me an error during execution.
Can anyone help me?
Thank you
Code behind
string InsMus = "Insert into StoreMus (MusNo,MusDate)" +
"Values (" + Convert.ToInt16(txtMusNo.Text) + ",'" + DateTime.Parse(txtMusDate.Text) + "')";
cmd = new SqlCommand(InsMus , con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Don't use string concanation to prevent sql injection. I'm sure that it will also fix this issue.
string InsMus = #"Insert into StoreMus (MusNo,MusDate)
Values (#MusNo, #MusDate);";
using(var con = new SqlConnection("Connection String..."))
using(var cmd = new SqlCommand(InsMus, con))
{
cmd.Parameters.Add("#MusNo", SqlDbType.SmallInt).Value = short.Parse(txtMusNo.Text);
cmd.Parameters.Add("#MusDate", SqlDbType.Date).Value = DateTime.Parse(txtMusDate.Text);
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
Note that i've used the using-statement to ensure that the connection gets disposed/closed.
You could also use DateTime.TryParse instead of DateTime.Parse to prevent an exception that happens when the format of the date is invalid:
DateTime musDate;
if(!DateTime.TryParse(txtMusDate.Text, out musDate))
{
MessageBox.Show("Please enter a valid mus-date.");
return;
}
// here you can use musDate

C# Windows Form App With Ms Access Failed to Insert Data

i know this topic is already discuss many time, but i still dont get my problem solved..
ok, i have a form to insert registration data into MS Access Database (2007), but my code doesnt insert data into database, and there are no errors,
here is the code:
OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb");
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
private void btnSave_Click(object sender, EventArgs e)
{
string idCard = this.txtID.Text;
string name = this.txtName.Text;
DateTime dateBirth = this.dateEdit1.DateTime;
cn.Open();
cmd.CommandText = "Insert into tb_reg (id, name, dateBirth, blood_type) Values(#id,#name,#dateBirth)";
cmd.Parameters.AddWithValue("#id", idCard);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#dateBirth", dateBirth.ToString());
adapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Succesfully added");
else
MessageBox.Show("try again");
cn.Close();
}
the message box always show "successfully added".
I had something like this in a project of mine. Maybe it works for you:
string insertString = string.Format(CultureInfo.InvariantCulture, "INSERT INTO tb_reg VALUES ('{0}', '{1}', '{2}', {3})", idCard, name, dateBirth, blood_type);
OleDbCommand cmd = new OleDbCommand(insertString, new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb"));
cmd.Connection.Open();
int numberAdded = cmd.ExecuteNonQuery();
if (numberAdded < 1)
{
//do something, the data was not added
}
else
{
//be happy :)
}
cmd.Connection.Close();
As I said, that worked for me.
The OleDB provider does not support named parameters. Change your SQL to
cmd.CommandText = #"Insert into tb_reg (id, name, dateBirth, blood_type)
Values(?,?,?,?)";
You can name the parameters when you create them, but it will assign them to the ? placeholders in the order that they are added to the command.
Also note that you're missing a parameter for blood_type.
Whatever you do, DON'T change to use string concatenation. It open the door for SQL Injection attacks.

how to get the last record number after inserting record to database in access

i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.

Categories

Resources