Inserting records into a Microsoft Access database in C# - c#

I am inserting data to access 2000-2003 file format database using C#. When I had a database with 2 fields the query works fine, but when there are more fields its is not working.
I have identical code for both and I am not able to find the problem.
using System.Data.OleDb; // By using this namespace I can connect to the Access Database.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private OleDbConnection myconn;
public Form1()
{
InitializeComponent();
myconn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\NewManageContacts.mdb");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
// this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
// TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// string query = "insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
cmd.CommandText = #"insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
cmd.Connection = myconn;
myconn.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myconn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
This is the code for the table with just 2 fields
public partial class Form1 : Form
{
private OleDbConnection myCon;
public Form1()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\Database1.mdb");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.Table1' table. You can move, or remove it, as needed.
this.table1TableAdapter.Fill(this.database1DataSet.Table1);
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 (name,fname) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myCon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
}
}

The extra fields you are trying to insert probably have values that don't readily concatenate into a valid SQL statement. For instance:
string field1 = "meh";
string field2 = "whatever";
string field3 = "'Ahoy!' bellowed the sailor.";
var cmd = new SqlCommand(
"INSERT INTO blah (x, y, z) VALUES ('" + field1 + "', '" + field2 + "', '" + field3 + '")");
Imagine what the concatenated SQL will look like, given the above input.
Worse, imagine the SQL you'll be executing if someone types this into your form:
field3 = "Bobby'); DROP TABLE Users; -- ";
Use parameterised queries via cmd.Parameters.Add or AddRange (described here). The above example might be emended thus:
var cmd = new SqlCommand("INSERT INTO blah (x, y, z) VALUES (#x, #y, #z)");
cmd.Parameters.AddRange(new[] {
new SqlParameter("#x", field1),
new SqlParameter("#y", field2),
new SqlParameter("#z", field2)
});

This code for public:
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Mohammadhoseyn_mehri\Documents\Data.mdb");
This code for singup button:
try
{
createaccount();
else
{
MessageBox.Show("Please re-enter your password");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("Data saved successfully...!");
con.Close();
}
This is the code for create account method:
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * from Login", con);
con.Open();
String ticketno = textBox2.Text.ToString();
String Purchaseprice = textBox1.Text.ToString();
String my_query = $"INSERT INTO Login (username, pass) VALUES ('{ticketno}', '{Purchaseprice}')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();

If you are working with databases, then mostly take the help of try-catch block statement, which will help and guide you with your code. Here I am showing you that how to insert some values in database with a button click event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_query = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}

private void btnSave_Click(object sender, EventArgs e)**
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into Personal (P_name, P_add,P_Phone)VALUES('" + txtName.Text + "','" +txtAddress.Text + "','" + txtPhone.Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
con.Close();
txtName.Text = "";
txtAddress.Text = "";
txtPhone.Text = "";
}

Related

Can't figure out what's wrong with my insert into statement to insert data from a windows forms textbox to a row in ms access database

public partial class Form1 : Form
{
static OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=chessclub.accdb");
static OleDbCommand cmd = con.CreateCommand();
static OleDbDataReader reader;
int count = 0;
public Form1()
{
InitializeComponent();
}
private void btncreate_Click(object sender, EventArgs e)
{
if (con.State.Equals(System.Data.ConnectionState.Open))
con.Close();
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO chess1db( names , schoolid , major , gender) + VALUES ( '" + txtname.Text + "','" + txtid.Text + "','" + txtmajor.Text + "','" + txtgndr.Text + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("Record submitted ");
con.Close();
}
}
Every time I press the button to send data to the db it tells me there's a syntax error in my INSERT INTO statement. What's wrong with it?
It's the plus-sign. Remove it:
cmd.CommandText = "INSERT INTO chess1db( names , schoolid , major , gender) VALUES ('" + txtname.Text + "','" + txtid.Text + "','" + txtmajor.Text + "','" + txtgndr.Text + "')";
But do use parameters.

SDA.SelectCommand.ExecuteNonQuery(); System.Data.SqlClient.SqlException: 'Incorrect syntax near '{'.'

Here is the snapshot of error occurring, I don't know what I am doing wrong:
enter image description here
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
String query = "INSERT INTO STOCK_IN { SIN_No., PO_NO., Product_ID, Received_Date, Quantity } VALUES ('"+textBox1.Text+ "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query , con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("DATA INSERTED SUCCESSFULLY");
}
The curly brackets are incorrect syntax. Also try something like this to handle this insert and catch errors. Also there is a trailing period after SIN_NO and I don't know if that is part of your column name or a typo.
private void Form1_Load(object sender, EventArgs e)
{
String query = "INSERT INTO STOCK_IN(SIN_No., PO_NO., Product_ID, Received_Date, Quantity) VALUES (#val1, #val2, #val3, #val4, #val5)";
SqlDataAdapter sda = new SqlDataAdapter();
try
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
cmd.Parameters.Add("#val1", SqlDbType.VarChar).Value = textBox1.Text;
//Then the same for 2, 3, 4, 5
sda = cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
MessageBox.Show("DATA INSERTED SUCCESSFULLY");
}
}
Step 1: change the {} to ().
Step 2: The problem is your column names have special characters. Use [ ] to specify the column name which contains the special character (like dot). Try this; it will solve your problem.
INSERT INTO STOCK_IN ([SIN_No.],[PO_NO.], Product_ID, Received_Date, Quantity)
VALUES ('"+ textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" +textBox4.Text + "','" + textBox5.Text + "')
Try changing the { to ( same with the closing one. So INSERT INTO STOCK_IN ( and close it with ) rather than }.
INSERT INTO STOCK_IN( SIN_No., PO_NO., Product_ID, Received_Date, Quantity)

How to insert a different selectedindex combobox value into database?

In my project i have a countries combobox (PaysCmBx0) that is filled from countries database table [Pays] column [pays], what i want to do is when i select a country in the combobox it insert the Alpha country code token from the Alpha country code column [Alpha2] in another table (exemple : United-states = US).
so when i select a country from the combobox it does nothing it's intserting the same value.
My table look like this:
[Aplha2] [Pays]
GB United Kingdom
IM Isle of Man
TZ United Republic Of Tanzania
US United States
BF Burkina Faso
UY Uruguay
UZ Uzbekistan
here's my code :
void Fillcombo()
{
string Query = "SELECT * FROM Pays";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd.ExecuteReader();
while (myRead.Read())
{
string sName = myRead["Pays"].ToString();
PaysCmBx0.Items.Add(sName);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void AddBtn_Click(object sender, EventArgs e)
{
try
{
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + TypeAdrCmBx.Text+ "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + this.PaysCmBx0.Text + "')";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
SqlDataReader Read;
try
{
Read = cmd.ExecuteReader();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PaysCmBx0_SelectedIndexChanged(object sender, EventArgs e)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
string Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
thanks every one i fund a solutions for this :
i create a function that gets the country code corresponding to what's selected in the combobox:
private string get_code_pays(string nom_pays)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
string Code_Pays="";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
return Code_Pays;
}
and then call my funtion with the parameter in my insert:
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + A + "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + get_code_pays( this.PaysCmBx0.Text) + "')";

ASP.net database code using c#

Please tell me the error in this code, the data is not stored in the table.
SqlConnection con;
SqlCommand com;
string constr = #"Data Source=SQL5004.myASP.NET;Initial Catalog=DB_9F2D70_arjunb98;User Id=DB_9F2D70_arjunb98_admin;Password=#;";
protected void submit_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection(constr);
con.Open();
com = new SqlCommand();
com.CommandText = "insert into table values ('" + DropDownList2.SelectedValue + "', '" + DropDownList1.SelectedValue + "','" + name.Text + "','" + mail.Text + "', '" + Address.Text + "', '" + DropDownList3.SelectedValue + "', '" + ph.Text + "','" + message.Text + "')";
com.Connection = con;
com.ExecuteNonQuery();
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(
Page.GetType(),
"MessageBox", "<script language='javascript'>alert('Sorry! the data is not Submitted, Please try again ')</script>");
}
finally
{
con.Close();
}
Aahhhhh. You have messed up your code. Also you have not shown your aspx so I am not much aware of the parameters you are using.
Also as suggested by Tim your code is prone to SQL Injection. So its better to used parameterized queries(recommended in your case)
So a simple reference with your code will be as below:-
On ButtonClick you may write something like below
protected void submit_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=SQL5004.myASP.NET;Initial Catalog=DB_9F2D70_arjunb98;User Id=DB_9F2D70_arjunb98_admin;Password=#;"); // connection string described by you
SqlCommand cmd = new SqlCommand("insert into Person(Column1,Column2,Column3,....) values(#Column1, #Column2, #Column3,...)", conn);
cmd.Parameters.AddWithValue("#Column1", TextBoxID.text); // it may be option as per your requirement(ex:- Dropdownlist)
cmd.Parameters.AddWithValue("#Column2", textbox2.Text);
cmd.Parameters.AddWithValue("#Column3", textbox3.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
label.Text = "Error when saving on database";
conn.Close();
}
// Empty your controls here
Control1.text = "";
Control2.text = "";
Control3.text = "";
}
There are also many other links available for your requirement.
http://www.aspsnippets.com/Articles/Using-Parameterized-queries-to-prevent-SQL-Injection-Attacks-in-SQL-Server.aspx
Hope that helps and clarifies your doubt too.
Happy learning :)

I want to get an alert if email already exits in my database in c# with help of execute scalar method

protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("select EmailID from Reg where EmailID='" + txtEmail.Text + "'", con);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar();
if (count==0)
{
Response.Write("email already Exists");
Response.End();
}
else
{
cmd.CommandText = "insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtMobile.Text + "','" + RdoGender.SelectedItem.Value + "','" + db + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
Please help me with this. And also for errors like use new keyword to create an object instance that I’m getting.
Put a unique index on EmailID, then perform just the insert and catch for SqlExceptions and check if exception.Number == 2601
Note: Use using statements to ensure that IDisposables will be disposed and use parameterized commands!
protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
using(SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values(#FirstName,#LastName,#Email,#Mobile,#Gender,#Db)", con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//Do the same with other parameters
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Number == 2601) // If instead of unique index, you have a unique constraint/primary key, check for ex.number==2627
{
// Duplicate key! Do whatever you want
}
}
}
}
}

Categories