myReader looking for .mdb and not .accdb - c#

im currently in my first year on university and c# is relatively new to me.
im currently working on accessing a database through a form for a made up company for one of my assignments and I cant get through an error that returns saying that myReader is trying to find the database called Jap1.mdb even though the database I have it linked to and successfully connecting to called Jap1.accdb.
the connection to the database works fine as I have a datagrid that produces all the information in the database and allows me to search through it so I am unsure as to why it is trying to find Jap1.mdb
this is the code I currently have in my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace customer_play
{
public partial class customersfrm : Form
{
OleDbConnection myConn;
OleDbDataAdapter myDataAdapter;
OleDbCommandBuilder cb;
DataSet ds;
string myConnection;
public customersfrm()
{
InitializeComponent();
}
private void customersfrm_Load(object sender, EventArgs e)
{
myConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "jap1.accdb";
myConn = new OleDbConnection(myConnection);
myDataAdapter = new OleDbDataAdapter();
myDataAdapter.SelectCommand = new OleDbCommand(" select * Jap1.CustomerDetails ;", myConn);
cb = new OleDbCommandBuilder(myDataAdapter);
myConn.Open();
ds = new DataSet();
myConn.Close();
}
private void addcustbtn_Click(object sender, EventArgs e)
{
string Query = "insert into Jap1.CustomerDetails (myFirstName,mySecondName,myAddress,myCity,myPostCode,myNumber,myEmailAddress,myDateOfBirth,my18Plus) values('" + this.firstnametxt.Text + "','" + this.secondnametxt.Text + "', '" + this.addresstxt.Text + "', '" + this.citytxt.Text + "', '" + this.postcodetxt.Text + "', '" + this.numbertxt.Text + "', '" + this.emailtxt.Text + "', '" + this.dobpicker.Text + "', '" + this.eighteenchkbx.Checked + "') ;";
OleDbCommand cmdDataBase = new OleDbCommand(Query, myConn);
OleDbDataReader myReader;
try {
myConn.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("New Customer Has Been Added To The Database");
firstnametxt.Text = "";
secondnametxt.Text = "";
addresstxt.Text = "";
citytxt.Text = "";
postcodetxt.Text = "";
numbertxt.Text = "";
emailtxt.Text = "";
dobpicker.Text = "";
eighteenchkbx.Text = "";
while(myReader.Read()){
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
}
}
any help would be hugely appreciated :)

Related

when maxlevel equal 0 prevent user from add this item

I set maxlvl to 5000, so it is decreasing when you take out product
maxlvl mean for every product you have the limit (maxlvl=5000) in like month
I want to set condition when maxlvl = 0 prevent user from taking this product
I'm new and I don't know how to link condition with db and which condition should i use
note: I'm learning and i don't care about SQL injection right now and I want to keep the code simple
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication7
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'invoiceDataSet12.product' table. You can move, or remove it, as needed.
this.productTableAdapter.Fill(this.invoiceDataSet12.product);
using (invoiceEntities2 cc1 = new invoiceEntities2())
{
productBindingSource.DataSource = cc1.product.ToList();
}
}
private void save_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NAWAF;Initial Catalog=invoice;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [invoice].[dbo].[Qout]
([id]
,[empnumber]
,[pname]
,[cproduct]
,[qnt])
VALUES
('" + tid.Text + "' ,'" + temp.Text + "' , '" + pcom.Text + "' , '" + pcomc.Text + "' , '" + qotext.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select id,empnumber,pname,cproduct,qnt from Qout where id like '" + tid.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
SqlCommand ccm = new SqlCommand("UPDATE product SET quantity -= '" + qotext.Text + "' FROM product WHERE Product_name like '" + pcom.Text + "'", con);
ccm.ExecuteNonQuery();
SqlCommand bbc = new SqlCommand("UPDATE product SET Maxlvl -= '" + qotext.Text + "' FROM product WHERE Product_name like '" + pcom.Text + "'", con);
bbc.ExecuteNonQuery();
temp.Text = "";
pcom.Text = "";
pcomc.Text = "";
qotext.Text = "";
con.Close();
}

the connectionstring property has not been initialized; Data type mismatch in criteria expression; database not updating

I'm new to c# and the "the connectionstring property has not been initialized" is my problem. I've searched and tried everything I saw on the internet, but it doesn't help me at all. I don't know what to do anymore, Please help :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace salon
{
public partial class Form4 : Form
{
OleDbConnection conn = new OleDbConnection();
public Form4()
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/myDB.accdb";
}
private void Form4_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDBDataSet.tblCustomerInfo' table. You can move, or remove it, as needed.
this.tblCustomerInfoTableAdapter.Fill(this.myDBDataSet.tblCustomerInfo);
}
private void btnContinue_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into tblCustomerInfo(CustomerName, PhoneNo, Email) values ('" + txtName.Text + "','" + txtNo.Text + "','" + txtEmail.Text + "'";
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
string date = System.DateTime.Today.ToString("ddmmyy");
MessageBox.Show("Your Information: " + Environment.NewLine + "Name: " + txtName.Text + Environment.NewLine + "Phone no.: " + txtNo.Text + Environment.NewLine + "Email: " + txtEmail.Text + Environment.NewLine + Environment.NewLine + "Your chosen date is: " + timePicker.Value);
MessageBox.Show("Your date is successfully reserved");
Form1 frm1 = new Form1();
frm1.Show();
this.Hide();
}
}
}
Please help me with this one, I am new to c# and I don't know how to fix this. I tried searching and all but no luck. #un-lucky suggested parameterized queries but i don't know how to. I tried searching for it and no luck.
data type mismatch
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace salon
{
public partial class Form4 : Form
{
OleDbConnection conn = new OleDbConnection();
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDBDataSet.tblCustomerInfo' table. You can move, or remove it, as needed.
this.tblCustomerInfoTableAdapter.Fill(this.myDBDataSet.tblCustomerInfo);
}
private void btnContinue_Click(object sender, EventArgs e)
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/myDB.accdb";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = conString;
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into tblCustomerInfo(CustomerName, PhoneNo, Email) values ('" + txtName.Text + "','" + txtNo.Text + "','" + txtEmail.Text + "')";
cmd.Parameters.AddWithValue("#CustomerName", txtName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", txtNo.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Your Information: " + Environment.NewLine + "Name: " + txtName.Text + Environment.NewLine + "Phone no.: " + txtNo.Text + Environment.NewLine + "Email: " + txtEmail.Text + Environment.NewLine + Environment.NewLine + "Your chosen date is: " + timePicker.Value);
MessageBox.Show("Your date is successfully reserved");
Form1 frm1 = new Form1();
frm1.Show();
this.Hide();
}
}
}
UPDATE
I fixed the error about the data type mismatch but now when i start to debug it the database is not updating what's wrong? please help
You have to initialize the ConnectionString property of the OleDbCommand, for that you can use the constructor or else you can initialize them later by setting the corresponding value to the property. Let conString be a global string variable which is used to store the connection string and are initialized like the following:
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/myDB.accdb"
Now you can define the connection like this
OleDbConnection conn = new OleDbConnection(conString );
or like this:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = conString;
Few other things that you have to notice is that:
You have syntax errors in your insert query, that means you missed the closing bracket at the end of the query.
Actually, using plain text queries will not be a good option, I strongly recommend you to use parameterization instead.

CheckBox Not Sending Checked Value to Access Database C# Asp

This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";

trying to create a refreshing button for gridview

I have made an c# program to access a database and write some data to it, and show it in a grid-view.
That all works but now i want the grid-view to refresh because it wont show the data i just entered into the database
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace ForexDev
{
public partial class Form1 : Form
{
private OleDbConnection Database1;
private OleDbCommand oledbcmd = new OleDbCommand();
private string connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\floortje\Documents\Visual Studio 2010\Projects\ForexDev\ForexDev\Database11.accdb;Persist Security Info=False";
public Form1()
{
Database1 = new OleDbConnection(connParam);
InitializeComponent();
}
private void btnsave_Click(object sender, EventArgs e)
{
try
{
Database1.Open();
oledbcmd.Connection = Database1;
oledbcmd.CommandText = "INSERT INTO Forex ([Order],[Tijd gekocht],Type,Groote,Symbool,[Koers inkoop],[S/l],[T/p],[Koers Verkoop],[Profit/Loss]) VALUES ('" + this.txtOrder.Text + "','" + this.txtTijd.Text + "','" + this.txtType.Text + "','" + this.txtgroote.Text + "','" + this.txtSymb.Text + "','" + this.txtKoop.Text + "','" + this.StopLoss.Text + "','" + this.TakeProfit.Text + "','" + this.txtVerkoop.Text + "','" + this.Winstverl.Text + "');";
oledbcmd.CommandType = CommandType.Text;
int temp = oledbcmd.ExecuteNonQuery();
dataGridView1.Refresh();
dataGridView1.Update();
Database1.Close();
if (temp > 0)
{
MessageBox.Show("Added");
}
else
{
MessageBox.Show("Failed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database11DataSet.Forex' table. You can move, or remove it, as needed.
this.forexTableAdapter.Fill(this.database11DataSet.Forex);
}
private void button2_Click(object sender, EventArgs e)
{
Database1.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Database1.Open();
this.dataGridView1.Refresh();
this.dataGridView1.Update();
Database1.Close();
}
}
}
I want to thank you tariq for putting me on the right track, i did not mark your answer as the answer to my problem because of the following :
The answer to my problem was that i needed to bind the database to the gridview like this :
(and correct me if this is not databinding)
{
Database1.Open();
oledbcmd.Connection = Database1;
oledbcmd.CommandText = textBox1.Text;
oledbcmd.CommandText = "DELETE FROM Forex ([Order],[Tijd gekocht],Type,Groote,Symbool,[Koers inkoop],[S/l],[T/p],[Koers Verkoop],[Profit/Loss]) VALUES ('" + this.txtOrder.Text + "','" + this.txtTijd.Text + "','" + this.txtType.Text + "','" + this.txtgroote.Text + "','" + this.txtSymb.Text + "','" + this.txtKoop.Text + "','" + this.StopLoss.Text + "','" + this.TakeProfit.Text + "','" + this.txtVerkoop.Text + "','" + this.Winstverl.Text + "');";
oledbcmd.CommandType = CommandType.Text;
int temp = oledbcmd.ExecuteNonQuery();
dataGridView1.DataSource = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\floortje\Documents\Visual Studio 2010\Projects\ForexDev\ForexDev\Database11.accdb;Persist Security Info=False";
dataGridView1.Refresh();
this.dataGridView1.Refresh();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter dd = new OleDbDataAdapter();
dd = new OleDbDataAdapter("Select * From Forex", Database1);
dd.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
Database1.Close();
Add this after making updates
dataGridView1.DataBind();

how to insert data if it contain apostrophe?

Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace tool
{
public partial class Form1 : Form
{
StreamReader reader;
SqlConnection con;
SqlCommand cmd;
int count = 0;
//int id=0;
FileStream fs;
string file = null;
string file_path = null;
SqlCommand sql_del = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog();
file1.ShowDialog();
textBox1.Text = file1.FileName.ToString();
file = Path.GetFileName(textBox1.Text);
file_path = textBox1.Text;
fs = new FileStream(file_path, FileMode.Open, FileAccess.Read);
}
private void button2_Click(object sender, EventArgs e)
{
if (file != null )
{
sql_del = new SqlCommand("Delete From credit_debit1", con);
sql_del.ExecuteNonQuery();
reader = new StreamReader(file_path);
string line_content = null;
string[] items = new string[] { };
while ((line_content = reader.ReadLine()) != null)
{
if (count >=4680)
{
items = line_content.Split(',');
string region = items[0].Trim('"');
string station = items[1].Trim('"');
string ponumber = items[2].Trim('"');
string invoicenumber = items[3].Trim('"');
string invoicetype = items[4].Trim('"');
string filern = items[5].Trim('"');
string client = items[6].Trim('"');
string origin = items[7].Trim('"');
string destination = items[8].Trim('"');
string agingdate = items[9].Trim('"');
string activitydate = items[10].Trim('"');
if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber)))
{
invoicenumber = "null";
}
else
{
invoicenumber = "'" + invoicenumber + "'";
}
if ((destination == "-") || (string.IsNullOrEmpty(destination)))
{
destination = "null";
}
else
{
destination = "'" + destination + "'";
}
string vendornumber = items[11].Trim('"');
string vendorname = items[12].Trim('"');
string vendorsite = items[13].Trim('"');
string vendorref = items[14].Trim('"');
string subaccount = items[15].Trim('"');
string osdaye = items[16].Trim('"');
string osaa = items[17].Trim('"');
string osda = items[18].Trim('"');
string our = items[19].Trim('"');
string squery = "INSERT INTO credit_debit1" +
"([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " +
"[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " +
"[OverUnderRecovery] ) " +
"VALUES " +
"('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," +
"'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," +
"'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') ";
cmd = new SqlCommand(squery, con);
cmd.CommandTimeout = 1500;
cmd.ExecuteNonQuery();
}
label2.Text = count.ToString();
Application.DoEvents();
count++;
}
MessageBox.Show("Process completed");
}
else
{
MessageBox.Show("path select");
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;");
con.Open();
}
}
}
vendername field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data
Use prepared statements, in this case SqlParameterCollection.AddWithValue or equivalent. There are a variety of tutorials available for this.
You are very naughty for building your sql statements that way, Santa Claus is definitely not going to visit you this year. Doing queries the way you are is opening yourself to sql injection attacks, intentional and unintentional as you've discovered with the '.
You should use parameterized query strings or stored procedures.
const string connString = "Data Source=localhost;Initial Catalog=OnlineQuiz;Integrated Security=True";
static void Main(string[] args)
{
string query = string.Format("SELECT * FROM [User] WHERE name like #name");
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#name", "F%");
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetValue(1));
}
}
}
}
}
You need to escape the apostrophe by adding a second apostrophe:
vendorname = vendorname.Replace("'", "''");
Disclaimer: Writing a raw SQL statement without using parameters is dangerous. Ideally, you should write a full SQL insert statement with assumed parameters, and instead of concatenating the value directly into the string, pass it in as a parameter:
string parameterizedSQL = "insert into credit_debit1 (id,region,station) values (#count, #region,#station)";
SqlCommand cmd = new SqlCommand(parameterizedSQL, con);
cmd.Parameters.Add("#count", SqlDbType.Int).Value = count;
cmd.Parameters.Add("#region", SqlDbType.VarChar).Value = region;
cmd.Parameters.Add("#station", SqlDbType.VarChar).Value = station;
cmd.ExecuteNonQuery();

Categories

Resources