how to using INSERT INTO in c# for access database - c#

This is mycode
please help me
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|members list.mdb");
OleDbCommand cmdoledb = new OleDbCommand();
con.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Members(name,family,age,Juncture scholarships) values('" + t1.Text + "','" + t2.Text + "','" + t3.Text + "','" + t4.Text + "')",con);
cmd.ExecuteNonQuery();
show();
t1.Text = string.Empty;
t2.Text = string.Empty;
t3.Text = string.Empty;
t4.Text = string.Empty;
}
private void show()
{
string d;
OleDbConnection con;
OleDbDataAdapter adap;
DataSet ds = new DataSet();
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|members list.mdb");
d = "select * from members";
adap = new OleDbDataAdapter(d, con);
adap.Fill(ds, "members");
dataGridView1.DataSource = ds.Tables["members"];
}
When I use this code I get this error
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.

2 things:
Use Parameters
When field name contains spaces use brackets
OleDbCommand cmd = new OleDbCommand("INSERT INTO Members(name,family,age,[Juncture scholarships]) values(#name,#family,#age,#Js)",con);
cmd.Parameters.AddWithValue("#name",t1.Text);
cmd.Parameters.AddWithValue("#family",t2.Text);
...
cmd.ExecuteNonQuery();
...

Related

How to fix System.IndexOutOfRangeException: Cannot find table 0 ASP.NET

[WebMethod()]
public DataTable insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode,int pack,string error,string chk,string user,DateTime day,string ekb,string kbid)
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = null;
StringBuilder strSQL = new StringBuilder();
strConnString = "Server=localhost;UID=sa;PASSWORD=12345678;database=bds_pp_srct;Max Pool Size=400;Connect Timeout=600;";
strSQL.Append("INSERT INTO Hanheld (Part_Number,SRCT_Code,Dock_Code,Package,Error_Code,Chk_Type,LogUser,LogDate,ekb_order_no,Kanban_ID) VALUES ('" + partnumber + "','" + srctcode + "','" + dockcode + "','" + pack + "','" + error + "','" + chk + "','" + user + "','" + day + "','" + ekb + "','" + kbid + "') ");
//strSQL.Append(" WHERE [SRCT_Code] = '" + strCusID + "' ");
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL.ToString();
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds);
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
return dt;
}
This error :
System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
Try this one
private DataTable dataTable = new DataTable();
string connString = #"query string here";
string query = "select table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();
I think you are using DataSet in your code might be there would be a problem
so you first need to check where that DataSet contains datatable at 0 location
eg.
DataSet ds = new DataSet();
dtAdapter.Fill(ds);
if(ds != null && ds.Tables.Count > 0) {
//your logic
}
[WebMethod()]
public void insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode)
{
using (SqlConnection conn = new SqlConnection("Server=localhost;UID=sa;PASSWORD=12345678;database=Test;Max Pool Size=400;Connect Timeout=600;"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Hanheld(Part_Number,SRCT_Code,Dock_Code) VALUES(#partnumber,#srctcode,#dockcode)";
cmd.Parameters.AddWithValue("#partnumber", partnumber);
cmd.Parameters.AddWithValue("#srctcode", srctcode);
cmd.Parameters.AddWithValue("#dockcode", dockcode);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// MessgeBox.Show(e.Message.ToString(), "Error Message");
}
}
}
}
This my Be fixed

Trying to parse csv file into access database c#

I've been working on this function to take a user selected csv file and parse it into an access database. After much trial and error and reading here, the thing will compile and run without crashing but no values are being inserted into the table. This I where I am at currently.
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
productFileName = productOpenDialog.SafeFileName;
productFilePath = Path.GetDirectoryName(productOpenDialog.FileName);
string connectionString = String.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source ={0}"+"\\VendorDB.accdb;Persist Security Info = False;", Environment.CurrentDirectory);
string selectSQL = String.Format(#"SELECT * FROM [" + productFileName + "]");
using (OleDbConnection connection = new OleDbConnection(String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Text;", productFilePath)))
{
using (OleDbCommand command = new OleDbCommand(selectSQL, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
//create connection to Access DB
OleDbConnection DBconn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
//set cmd settings
cmd.Connection = DBconn;
//cmd.CommandType = CommandType.Text;
//open DB connection
DBconn.Open();
//read each row in the Datatable and insert that record into the DB
for (int i = 0; i < dataTable.Rows.Count; i++)
{
cmd.CommandText = "INSERT INTO Product_List (ProductID, ProductName, Description, InventoryItem, Price, CaseSize, SalespersonID)" +
" VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) +
"','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) +
"','" + dataTable.Rows[i].ItemArray.GetValue(6) + "')";
cmd.ExecuteNonQuery();
}
//close DB.connection
DBconn.Close();
}
}
}
}
I am aware that datatypes in fields might be an issue, so I removed a DateTime and changed price to a short number, so all data is strings and numbers. Despite successfully loading the DataTable from the csv file, no values are inserted into access.

syntax error (missing operator) in query expression

I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.

Login and password in asp

i have a par of code c# to login but doesn't work it gives me the message in Else :
protected void Button1_Click(object sender, EventArgs e)
{
string Connection = #"data source=LOCALHOST;initial catalog=CVtech;Integrated Security=false;User ID=sa;Password=123";
string Requete = "select * from Agent where Login ='" + UserLogin.Text + " and PPR = " + UserPass.Text+"'";
SqlDataAdapter da = new SqlDataAdapter(Requete, Connection);
DataSet Ds = new DataSet();
da.Fill(Ds);
if (Ds.Tables[0].Rows.Count > 0)
{
DataRow[] dr = Ds.Tables[0].Select();
Session["Code"] = dr[0]["PPR"].ToString();
Response.Redirect("cv.aspx");
}
else
{
Response.Write(" message d'erreur login et mot de passe erroné");
}
}
i have a login : "Ach" and PPR = 1
Thank you
You're not closing the string value in the sql request.
string Requete = "select * from Agent where Login ='" + UserLogin.Text + " and PPR = " + UserPass.Text + "'";
should be
string Requete = "select * from Agent where Login ='" + UserLogin.Text + "' and PPR = '" + UserPass.Text + "'";
Also, you should look into sql injection and parametrizing your queries. I don't use DataAdapters much but I believe it will look something like.
SqlConnection connection = new SqlConnection("data source=LOCALHOST;initial catalog=CVtech;Integrated Security=false;User ID=sa;Password=123");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand command = new SqlCommand("select * from Agent where Login = #login and PPR = #ppr", connection);
command.Parameters.Add("#login", SqlDbType.NVarChar, 50);
command.Parameters["#login"].Value = UserLogin.Text;
command.Parameters.Add("#ppr", SqlDbType.NVarChar, 50);
command.Parameters["#ppr"].Value = UserPass.Text;
da.SelectCommand = command;
DataSet Ds = new DataSet();
da.Fill(Ds);
For more details see
How To: Protect From SQL Injection in ASP.NET
http://msdn.microsoft.com/en-us/library/ff648339.aspx
SqlDataAdapter.SelectCommand Property
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx

import xml to mdb

I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------

Categories

Resources