I am Using MS Access DataBase.
I am trying to add Data in the table, But After adding a column id AutoNumber in the table. it gives an error. Please Guide me How I can solve this.
private void button1_Click_1(object sender, EventArgs e)
{
OleDbConnection sc = new OleDbConnection(connectionString);
OleDbCommand sm = new OleDbCommand("insert into prod values('" + textBox13.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox10.Text + "','" + textBox11.Text + "','" + textBox12.Text + "')", sc);
//SqlCommand sm = new SqlCommand("insert into prod values(N'" + textBox1.Text + "',N'" + textBox2.Text + "',N'" + textBox3.Text + "',N'" + textBox4.Text + "',N'" + textBox5.Text + "',N'" + textBox6.Text + "',N'" + textBox7.Text + "',N'" + textBox8.Text + "',N'" + textBox9.Text + "',N'" + textBox10.Text + "',N'" + textBox11.Text + "',N'" + textBox12.Text + "',N'" + textBox13.Text + "')", sc);
sc.Open();
sm.ExecuteNonQuery();
//sm.ExecuteNonQuery();
sc.Close();
}
Error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Data type mismatch in criteria expression.
Always uses parameters to properly type data for inserts, updates, deletes and select/where.
Example
using System;
using System.Data.OleDb;
using System.Windows.Forms;
namespace AccessSamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void AddButton_Click(object sender, EventArgs e)
{
var (exception, identifier) = DataOperations.Add(
"New company",
"Some contact",
DateTime.Now);
if (exception is null)
{
MessageBox.Show($"New id {identifier}");
}
}
}
public class DataOperations
{
private static string _connectionString =>
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=NorthWind.accdb";
public static (Exception exception, int identifier) Add(string companyName, string contactName, DateTime modified)
{
try
{
using (var cn = new OleDbConnection { ConnectionString = _connectionString })
{
using (var cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName,Modified) " +
"VALUES (#CompanyName,#ContactName,#Modified)";
cmd.Parameters.Add(new OleDbParameter("#CompanyName", OleDbType.LongVarChar));
cmd.Parameters.Add(new OleDbParameter("#ContactName", OleDbType.LongVarChar));
cmd.Parameters.Add(new OleDbParameter("#Modified", OleDbType.Date));
cmd.Parameters["#CompanyName"].Value = companyName;
cmd.Parameters["#ContactName"].Value = contactName;
cmd.Parameters["#Modified"].Value = modified;
cn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT ##Identity";
return (null, Convert.ToInt32(cmd.ExecuteScalar()));
}
}
}
catch (Exception ex)
{
return (ex, -1);
}
}
}
}
Related
Am getting an error while inserting data from excel to the database table.
this is the error Incorrect syntax near 'NAME'
this is my code:
protected void btninsert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
conStr = ConfigurationManager.ConnectionStrings["SqlConString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("insert into MedicalItems (ITEM NAME,GROUP,ITEM TYPE,COST PRICE,SELLING PRICE,PURCHASE UOM,PURCHASE PACKAGING,DISPENSING UOM,QTY ON HAND,EXPIRY DATE,REORDER LEVEL,REORDER QUANTITY,BATCH#) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
Label2.Text = "Records inserted successfully";
}
Wrap the column names within [] like [ITEM NAME], for all the columns with whitespaces.
I'm using visual studio 2017 community and i'm trying to create local data base and I have a problem in the connection string since it dont connect when run it step by step its stuck in conn.Open();
this is the code of the connection and the executenonquery:
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
image screenshot of visual:
image screenshot
The entire code:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(??,???,?????,???? ?????,????,???? ?????,????,???,??)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
}
}
Use the connection string available in properties tab of the screenshot you have attached if the problem is of connection string
This is what I'm talking about
Use this as connection string, also remember to replace password value from '*' to actual value.
I have an error message when I'm trying to run the code and pass the information from a CSV file into the Local DataBase
the error message is :
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
and I'm not sure what is the problem in here:
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','"
+ rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6]
+ "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
image screenshot of visual:
image screenshot
when I run the app the LOCALDBSHILOV have a red X on him is it noraml
red X image
the code is:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('"
+ rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','"
+ rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
Your connection string is not correct. Use one like this:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
when i run it its stuck in conn.Open(); and does nothing and there is no error but the application continues to run only that it does not pass to the next line of code and there is no update of the table
try
{
//SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
I'm getting this error code: "unclosed quotation mark after the character string" on the line: cmd.ExecuteNonQuery();
I've looked, but I don't know what's wrong. I also tried just putting two of the textboxe, but I can't seem to debug it. Please advise. Thanks!
Here's the code:
namespace Inventory
{
public partial class NewData : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection("Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234");
protected void Page_Load(object sender, EventArgs e)
{
}//end page load
protected void addButton_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" + Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
cmd.ExecuteNonQuery();
cn.Close();
status.Visible = true;
status.Text = "Added succesffully!";
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//end add button
protected void clearButton_Click1(object sender, EventArgs e)
{
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//clear button
}//end
}//end
As far as I can see, you have unnecessary single quote at the end of your query.
Notestb.Text + "')'
^^ here
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 connections and commands automatically instead of calling Close or Dispose methods manually.
using(var cn = new SqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
// Set your CommandText property with your parameter definitions
// Add your parameters and their values with Add method
// Open your connection
// Execute your query.
}
Your command ends with an extra single quote. It should be:
cmd.CommandText = "INSERT INTO Inventory values('" +
Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text +
"','" + Serialtb.Text + "','" + Assignedtb.Text + "','" +
Locationtb.Text + "','" + Notestb.Text + "')";
I think the problem is
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" +
Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
there you single comma ' after the right bracket ).
Should have been:
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','"
+ Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text
+ "')";
I have a problem with insert into statement..
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");
ERROR : Syntax Error INSERT INTO
Anyone can advise me? Please, Sorry for my bad English grammar.
Seem like you are missing out a parameter in your query, try using this
cmd.CommandText = "insert into Table1 (id,Position) values (#id,#Position)";
cmd.parameters.addwithvalue("#id", textBox1.Text);
cmd.parameters.addwithvalue("#Position", combobox1.selectedvalue);
new updated
-the position is the oleh db reserved words, try change to this query, put the cover to Position like below
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,[Position],Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
You have missed adding #Photo parameter in your code.
That is ok for testing purpose but you should never insert to database this way. This expose your system to a SQL Injection. You should use parametrized queries where possible. Something like
int result=0;
using (OleDbConnection myConnection = new OleDbConnection ("YourConnectionString"))
{
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) values (#ID, #Gender, #DateOfBirth, #Race, #WorkingPlace, #PassportNO, #DateOfExpire, #Position, #Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#ID", textBox5.Text);
// Specify all parameters like this
try
{
con.Open();
result = Convert.ToInt32(cmd.ExecuteNonQuery());
}
catch( OledbException ex)
{
// Log error
}
finally
{
if (con!=null) con.Close();
}
}
if(result > 0)
// Show success message
Also note that OleDb parameters are positional, means you have to
specify them in the exact order as in your query. OleDbParameter Class (MSDN)
There is no value for parameter #Photo, and if your photo field is not nullable or empty
in database structure then how you can add null value in that.So make your data field
nullable or pass value to parameter #Photo.I think it will solve your problem.
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
cmd.Parameters.AddWithValue("#Photo", assignvalue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");