DateTime error type mismatch - c#

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

Related

Storing multiple values from an SQL select statement

I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated

Connecting to Access database

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();

Executing INSERT command into LocalDB

I have created a local Service-Based database and I'm trying to insert data to it with an INSERT statement:
public void InsertRule(Rule r)
{
SqlConnection sqlConnection1 = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\RulesDB.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = ("INSERT INTO TblRules (From, To, ExecutablePath) VALUES (#From, #To, #ExecutablePath");
cmd.Parameters.Add("#From",SqlDbType.DateTime);
cmd.Parameters["#From"].Value = r.From;
cmd.Parameters.Add("#To",SqlDbType.DateTime);
cmd.Parameters["#To"].Value = r.To;
cmd.Parameters.Add("#ExecutablePath",SqlDbType.Text);
cmd.Parameters["#ExecutablePath"].Value = r.ExecutablePath;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
I'm getting a SqlException:
Additional information: Incorrect syntax near the keyword 'From'.
Thanks in advance.
FROM is SQL keywoard, therefore you can't use it in a statement. You should escape it using square brackets [From]. That's what the error is about
That means you need to change this line
cmd.CommandText = ("INSERT INTO TblRules (From, To, ExecutablePath) VALUES (#From, #To, #ExecutablePath");
into
cmd.CommandText = (#"INSERT INTO TblRules ([From], To, ExecutablePath) VALUES (#From, #To, #executablePath);

Missing Required Parameter in Parameterized Query?

I am getting the following error trying to execute the code below
No Value Given For One Or More Required Parameters.
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = "SELECT [FUNCTION],[NAME] from [Sheet1$] WHERE [FUNTION] = ?";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connString;
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("?", paraName);
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd);
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
OleDbCommand does not support named parameters (see the docs). What you need to do is something like:
cmd.Parameters.Add(new OleDbParameter { Value = paraName });
Edit: I haven't tried it, but I suppose it might be possible to use your above code and pass null as the name argument...
James, I can see that you are trying to parametrize as you would with SQL. However OleDb wouldn't follow the exact pattern. In OleDb you can simply put question marks in your sql sentence and fill them up later using Parameter.Add().value which is quite straight forward.
As MSDN reference points out:
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.
I have rewritten your code in the way it should look like
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = string.Format("SELECT [{0}],[{1}] from [{2}] WHERE [{0}] = ?", strFunction, strName, strSheetName);
conn.ConnectionString = connString;
using (OleDbConnection conn = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameter.Add("#Param1", OleDbType.VarChar).Value = paraName; // paraName or any value you wish.
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd); //or cmd.ExecuteNonQuery(); in Insert sql commands.
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Note, You should put your OleDbConnection inside the using statement rather than your OleDbCommand.
I haven't tested it and it may contain some minor error. Other than that punch it there and press play (F5).
You can find more on OleDb parametrization from OleDbCommand.Parameters Property
Good luck and let us know what happens.

How to insert record into a sql server express database table?

I'm trying to insert a textbox value to a database table called site_list.
The site_list table contains two columns id and site_name, id set to auto increment
This is the code I'm trying and when it execute there is no error, but the data is not showing up in the table
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|scraper_db.mdf;";
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name) "
+ " VALUES (#site_name)", conn);
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
conn.Open();
addSite.ExecuteNonQuery();
conn.Close();
Any help would be appreciated.
Regards
Edit:
This code started to work
string connstring = "Data Source=.\\SQLExpress;"+
"Integrated Security=true;"+
"User Instance=true;"+
"AttachDBFilename=|DataDirectory|scraper_db.mdf;"+
"Initial Catalog=scraper_db";
using (SqlConnection connection = new SqlConnection(connstring))
{
connection.Open();
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name)"+
"VALUES (#site_name)", connection);
addSite.Parameters.AddWithValue("#site_name", textBox1.Text);
addSite.ExecuteNonQuery();
connection.Close();
}
as people suggests, try creating the database on the server (it will be even easier to handle using Sql Management Studio).
Once that's done, try the following (just tested and it works):
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO site_list (site_name) VALUES (#site_name)", conn);
addSite.Parameters.AddWithValue("#site_name", "mywebsitename");
addSite.Connection.Open();
addSite.ExecuteNonQuery();
addSite.Connection.Close();
}
try
{
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)\SQLEXPRESS;database=Inventory;Data Source=localhost\SQLEXPRESS;"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO Creation (Name,Product,Quantity,Category) VALUES (#Name,#Product,#Quantity,#Category)", conn);
addSite.Parameters.AddWithValue("#Name", textBox1.Text);
addSite.Parameters.AddWithValue("#Product", textBox2.Text);
addSite.Parameters.AddWithValue("#Quantity", textBox3.Text.ToString());
addSite.Parameters.AddWithValue("#Category", textBox4.Text);
thisConnection.Open();
addSite.ExecuteNonQuery();
}
}
catch
{
thisConnection.Close();
}
try this out :
string sql = String.Format("INSERT INTO site_list (site_name) VALUES('{0}')", myTextBox.Text);
using(SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.open();
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.ExecuteNonQuery();
}
}
Good luck
Try storing your textbox value in a variable. As in:
#stringname = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = #stringname;
(IMPORTANT! the # in #stringname is not necessary, but protects you against hackers!)
This code has worked wonders for me.
My apologies. The answer I gave previously will not work because the variable name used in the insert command (in your case #site_name) must match the variables used in your sqlcommand. As in:
#site_name = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
Sorry for the confusion I might have caused.

Categories

Resources