Inserting and Updating data to MDB - c#

I'm trying to make a simple test program that can open MDB files and do 3 basic things
the MDB have 3 fields, all of them are text:
ID
INFO
TEXT
showing data acording to ID = got this working
changing data according to ID = problem
adding new data = problem
the show data works with this code:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select Info, text from Table1 where ID = '" + int.Parse(textBox1.Text) + "' ";
con.Open(); // open the connection
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr["Info"].ToString();
textBox3.Text = dr["text"].ToString();
}
con.Close();
How do I insert new data in MDB and update data I already have?

Working code
using System;
using ADOX;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
CreateMdb("toster_ru.mdb");
string fileNameWithPath = Environment.CurrentDirectory + "\\toster_ru.mdb";
CreateTableInToMdb(fileNameWithPath);
InsertToMdb(fileNameWithPath);
UpdateToMdb(fileNameWithPath);
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0; Data Source = " + fileNameWithPath))
{
conection.Open();
var query = "Select info From my_table";
var adapter = new OleDbDataAdapter(query, conection);
adapter.Fill(myDataTable);
Console.WriteLine(myDataTable.Rows[0][0].ToString()); //output: toster2.ru
Console.ReadKey();
}
}
static void CreateMdb(string fileNameWithPath)
{
if (File.Exists(fileNameWithPath))
return;
Catalog cat = new Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
static void InsertToMdb(string fileNameWithPath)
{
var con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileNameWithPath);
var cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "insert into my_table (ID, [Info], [text]) values (#ID, #Info, #text);";
cmd.Parameters.AddWithValue("#ID", 1);
cmd.Parameters.AddWithValue("#Info", "toster.ru");
cmd.Parameters.AddWithValue("#text", "blabla");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
static void UpdateToMdb(string fileNameWithPath)
{
var con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileNameWithPath);
var cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE my_table SET [Info] = ?, [text] = ? WHERE ID = ?;";
cmd.Parameters.AddWithValue("#p1", OleDbType.VarChar).Value = "toster2.ru";
cmd.Parameters.AddWithValue("#p2", OleDbType.VarChar).Value = "blabla2";
cmd.Parameters.AddWithValue("#p3", OleDbType.VarNumeric).Value = 1;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
static void CreateTableInToMdb(string fileNameWithPath)
{
try
{
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileNameWithPath);
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "CREATE TABLE my_table([ID] NUMBER, [Info] TEXT, [text] TEXT)";
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch { }
}
}
}

Try this for insert:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "insert (ID, Info, text) into Table1 values (#ID, #Info, #text);";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
//OleDbDataReader dr = cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
con.Close();
Try this for update:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Table1 set [Info] = #Info, [text] = #text where ID = #ID;";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
//OleDbDataReader dr = cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
con.Close();
For more operations, examine the left panel of this site.

Related

How to Save 2 different Cell values into 2 different variables from database C#

I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}

Binary data displayed instead of image in c# and mysql

public void ProcessRequest(HttpContext context)
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString.ToString());
// Create SQL Command
int adid= int.Parse(context.Request.QueryString["adid"]);
int imgid = int.Parse(context.Request.QueryString["imgid"]);
MySqlCommand cmd = new MySqlCommand();
//cmd.CommandText = "Select i.image_id, i.image_name, i.image_byteImage, i.image_adId from images i,postadverties p where i.image_adId =#ID";
cmd.CommandText = "SELECT image_id,image_byteImage FROM images WHERE image_adId="+ adid + " and image_id="+ imgid;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
//MySqlParameter AdId = new MySqlParameter("#ID", MySqlDbType.Int32);
//MySqlParameter imgid = new MySqlParameter("#imgid", MySqlDbType.Int32);
//AdId.Value =
//imgid.Value =
//cmd.Parameters.Add(AdId);
//cmd.Parameters.Add(imgid);
con.Open();
MySqlDataReader dReader = cmd.ExecuteReader();
if (dReader.Read())
{
byte[] binaryimg = (byte[])dReader["image_byteImage"];
string base64string = "data:image/jpeg;base64," + Convert.ToBase64String(binaryimg);
context.Response.Write(base64string);
context.Response.Flush();
context.Response.End();
}
dReader.Close();
con.Close();
}
Click here to see result
When trying to display images stored in database above result is displayed instead of image.No clue why this issue is coming.Is there any problem while converting it or some else.In another page it works and on some pages it does not.

C# get access 2010 autonumber

Hi I am submitting a form to access but want to get the access assigned auto number to display in a textbox after I submit. Below it was i have, any suggestions would be great!
string cmdstr = "Insert into TaskPerformed(TaskType,OtherType,Analyst,DateCompleted)Values(#b,#c,#d,#e)";
string query2 = "Select ##IDENTITY";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con1);
OleDbCommand cmdNewID = new OleDbCommand("SELECT ##IDENTITY", con1);//
con1.Open();
cmd.CommandText = query2;
com.ExecuteNonQuery();
con1.Close();
label16.Text = cmdNewID.ToString();
It looks like the problem you're having is because you're not executing the second command... and you're closing the connection before using it
using(OleDbCommand cmdNewID = new OleDbCommand("SELECT ##IDENTITY", con1))
{
con1.Open();
cmd.CommandText = query2;
com.ExecuteNonQuery();
label16.Text = cmdNewID.ExecuteScalar();
}

DataRoutines not creating data in Access Database

today, I am trying to use DataRoutines to insert some values into my Access Database. However, it did not work as well as there were no records created. Does anyone know what's wrong with my code?
This is my DataRoutines (dataroutines2) file
public void CreateRecs(string strUserId)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
OleDbCommand cmd; OleDbDataReader rdr;
string strSql;
string strOFlag = "F";
// check to see if there is an active order record
strSql = "SELECT eStatus FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
Boolean booRows = rdr.HasRows;
if (booRows) //when booRows is true, there are order records for the user
{
rdr.Read();
if ((string)rdr["eStatus"] != "Ordering") //status of an active order is "Ordering"
{
strOFlag = "M"; //"T" means there is a need to create a new Orders record
}
else { strOFlag = "M"; }
mDB.Close();
if (strOFlag == "M")
{
//insert a new order record
string strStatus = "Ordering";
strSql = "INSERT INTO enrolInfo (eUserId, eStatus) VALUES (#UserId, #Status)";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.AddWithValue("#UserId", strUserId);
cmd.Parameters.AddWithValue("#Status", strStatus);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
}
//get back order No - this order no is needed when the user buys an item
strSql = "SELECT eEnrolNo FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
Session["tOrderNo"] = rdr["eEnrolNo"]; //store the active order no in the sOrderNo
mDB.Close();
return;
}
}
This is the code that will route the solution to the DataRoutines file in my Register Page
//prepare Session variables for newly register customer
Session["sFlag"] = "M";
Session["tUserId"] = (string)txtUserId.Text;
Session["tName"] = (string)txtName.Text;
Session["tAddress"] = (string)txtAddress.Text;
Session["tTel"] = (string)txtTel.Text;
Session["tEmail"] = (string)txtEmail.Text;
String strUserId = (string)Session["tUserId"];
DataRoutines2 DRObject = new DataRoutines2();
DRObject.CreateRecs(strUserId);
Thanks for your help

How do I go about adding records into TWO tables into Access Database?

I am a new member. Also, I am trying to add a record into 2 different tables (customerinfo & studentinfo). My code is below but it only records the textbox fields into the StudentInfo Table only. How should I go about it putting the record into 2 tables simultaneously?
Thanks
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
Type csType = this.GetType();
//check to ensure that UserId keyed in is not being used by other Customers
OleDbCommand cmd;
OleDbCommand cmd1;
OleDbDataReader rdr;
OleDbDataReader rdr1;
string strSQLSelect = "SELECT sUserId FROM studentInfo ORDER BY sUserId";
string strSQLSelect1 = "SELECT cUserId FROM customerInfo ORDER BY cUserId";
cmd1 = new OleDbCommand(strSQLSelect1, mDB);
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
rdr1 = cmd1.ExecuteReader();
this.txtPassword.Attributes.Add("value", this.txtPassword.Text);
// insert new record
string strSQLInsert = "INSERT INTO "
+ "studentInfo (sUserId,sPassword,sName,sAddress,sTel,sEmail,sLevel, sLevel2)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#lvl,#lvl2)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#tel", txtTel.Text);
cmd.Parameters.AddWithValue("#lvl", DropDownList1.Text);
cmd.Parameters.AddWithValue("#lvl2", DropDownList2.Text);
string strSQLInsert1 = "INSERT INTO "
+ "customerInfo (cUserId,cPassword,cName,cAddress,cEmail,cTel,cCountry)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#country)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd1 = new OleDbCommand(strSQLInsert1, mDB);
cmd1.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd1.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd1.Parameters.AddWithValue("#name", txtName.Text);
cmd1.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd1.Parameters.AddWithValue("#em", txtEmail.Text);
cmd1.Parameters.AddWithValue("#tel", txtTel.Text);
cmd1.Parameters.AddWithValue("#country", txtCountry.Text);
cmd.ExecuteNonQuery();
mDB.Close();
It looks like you're missing
cmd1.ExecuteNonQuery()
for the other table.

Categories