How to call a function in a command? - c#

I want to use the function "MyPlaces". What should I use instead of commandType.StoredProcedure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("MyPlaces", conn);
cmd.CommandType = CommandType.StoredProcedure; //This part gives me an error
string email = Session["oldemailuser"].ToString();
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string s = "<br />";
while (rdr.Read())
{
string name = s + " " + rdr.GetString(rdr.GetOrdinal("name"))
+ " located in ";
string location = rdr.GetString(rdr.GetOrdinal("location"))
+ " &nbsp";
Label lbl_name = new Label();
lbl_name.Text = email;
form1.Controls.Add(lbl_name);
Label lbl_location = new Label();
lbl_location.Text = email;
form1.Controls.Add(lbl_location);
}
}

Hope your sql function name is "Myplaces".If So,Then Modify your code with this :
string email = Session["oldemailuser"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(conn);
cmd.CommandText = "SELECT MyPlaces(#email)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();

Related

asp.net postgresql connection CRUD

I have a problem with data management in the postgre database. I`m connected, now i want to add any value, but that what i wrote dosent work.
protected void Page_Load(object sender, EventArgs e)
{
try
{
Label1.Text = "Połączenie z bazą danych zakonczońe sukcesem";
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "select * from magazynpaczek";
NpgsqlDataAdapter nda = new NpgsqlDataAdapter(comm);
DataTable dt = new DataTable();
nda.Fill(dt);
comm.Dispose();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
Label1.Text = "Połączenie z bazą danych zakonczońe niepowodzeniem";
}
}
protected void btnDodaj_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
string query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
NpgsqlCommand comm = new NpgsqlCommand(query, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
you have to create and add a parameter for each insert value:
var query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
IDbCommand command = conn.CreateCommand();
command.CommandText = query;
var parameter = command.CreateParameter();
parameter.ParameterName = "NFN";
parameter.Value = nfn;
command.Parameters.Add(parameter);
parameter = command.CreateParameter();
parameter.ParameterName = "txtIN";
parameter.Value = txtIN.text;
command.Parameters.Add(parameter);
.... and so on
conn.Open();
command.ExecuteNonQuery();
conn.Close();

Proper format for string and parse

I'm trying to do an add to cart function for my website but I'm getting an error when trying to convert a textbox number in to a value for visual studio to understand.
This is the error message:
(Link to full-size image)
This is my code
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class ProductDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
qtytxt.Attributes.Add("placeholder", "Your Quantity");
}
static readonly string scriptStockOut = "<script language=\"javascript\">\n" +
"alert (\"Sorry Stock Out! Please choose a smaller quantity or another product \");\n" +
"</script>";
static readonly string scriptErrorLogin = "<script language=\"javascript\">\n" + "alert (\"Please login or create account first to facilitate buying\");\n</script>";
protected void atcbtn_Click(object sender, EventArgs e)
{
string strProductId, strSQL;
int intQuantityOnHand, intBuyQuantity, newQty, intOrderNo;
decimal decUnitPrice;
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin); return;
}
SqlConnection sqlCon = new SqlConnection(#"Data Source=teafamily;Initial Catalog=BolsenF1;Integrated Security=True;MultipleActiveResultSets=true;");
sqlCon.Open();
Type csTypee = this.GetType();
SqlCommand sqlcmd;
SqlDataReader rdr;
string strSQLSelect = "SELECT pProductID FROM Products";
sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
rdr = sqlcmd.ExecuteReader();
DetailsViewRow row0 = DetailsView1.Rows[0];
strProductId = row0.Cells[1].Text;
strSQLSelect = "SELECT pQty FROM Products WHERE pProductID=#ProductID";
sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
object oQty = sqlcmd.ExecuteScalar();
intQuantityOnHand = (int)oQty;
strSQLSelect = "SELECT pPrice FROM Products WHERE pProductID=#ProductID";
sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
object oUnitPrice = sqlcmd.ExecuteScalar();
decUnitPrice = (decimal)oUnitPrice;
intBuyQuantity = int.Parse(qtytxt.ToString());
newQty = intQuantityOnHand - intBuyQuantity;
if (intQuantityOnHand < intBuyQuantity)
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "StockOut", scriptStockOut);
}
Session["sProductId"] = strProductId;
Session["sUnitPrice"] = decUnitPrice.ToString();
Session["sQuantity"] = newQty.ToString();
intOrderNo = (int)Session["sOrderNo"];
strSQL = "INSERT INTO orderItems(iOrderNo,iProductID, iQty, iUnitPrice)"
+ "VALUES (#OrderNo, #ProductID, #Qty, #UnitPrice)";
sqlcmd = new SqlCommand(strSQL, sqlCon);
sqlcmd.Parameters.AddWithValue("#OrderNo", intOrderNo);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
sqlcmd.Parameters.AddWithValue("#Qty", intBuyQuantity);
sqlcmd.Parameters.AddWithValue("#UnitPrice", decUnitPrice);
sqlcmd.ExecuteNonQuery();
strSQL = "UPDATE Products SET pQty=#NewQty WHERE pProductID = #ProductID";
sqlcmd = new SqlCommand(strSQL, sqlCon);
sqlcmd.Parameters.AddWithValue("#NewQty", newQty);
sqlcmd.Parameters.AddWithValue("#ProductID", strProductId);
sqlcmd.ExecuteNonQuery();
sqlCon.Close();
Response.Redirect("ShoppingCart.aspx");
}
}
I assume that qtytxt is a TextBox. If it is the case, you must use qtytxt.Text to access its text/value. The Text property of a TextBox contains its "user provided"/posted value.
So you should write :
intBuyQuantity = int.Parse(qtytxt.Text);
Don't forget to specify the expected CultureInfo to the appropriate int.Parse() method overload if necessary.

I can't update and insert to sql server but I can select data

I have some problem with update and insert data in sql server database BUT I can select data from it. I'm using visual studio 2012 , sql server 2012.
Please help ,Thank a lot.
This is my connectionstring in app.config
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;`enter code here`
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ProjectAppWIn
{
public partial class Refill : Form
{
ProjectAppWIn.Login.user s;
ProjectAppWIn.Home.userr r;
public string sa;
public string se;
public Refill(ProjectAppWIn.Login.user s1, ProjectAppWIn.Home.userr s2) //string user)
{
InitializeComponent();
s = s1;
// label2.Text = "Welcome : " + " " + (user);
sa = s.name;
//on which control you want to show the username....
label2.Text = "Welcome..." + s.name;
r = s2;
se = r.id;
textBox8.Text = r.id + "";
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form targetform = new Login();
targetform.Show();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con1 = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
if (textBox1.Text.Contains("g") || textBox1.Text.Contains("G") == true)
{
DataTable dte = new DataTable();
con1.Open();
SqlDataReader myRead = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + textBox1.Text + "'", con1);
SqlCommand myCom = new SqlCommand("select card_balance,card_id from card where guest_id = '" + textBox1.Text + "'", con1);
myRead = myCom.ExecuteReader();
while (myRead.Read())
{
textBox6.Text = (myRead["card_balance"].ToString());
textBoxcardid.Text = (myRead["card_id"].ToString());
//TextBox8.Text = (myReader[].ToString());
//DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
//DropDownListMonth.Text = (myReader["birth"].ToString());
//DropDownListYear.Text = (myReader["birth"].ToString());
//TextBoxAddress.Text = (myReader["address"].ToString());
//TextBoxCity.Text = (myReader["city"].ToString());
//DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
//TextBoxPostcode.Text = (myReader["postcode"].ToString());
//TextBoxEmail.Text = (myReader["email"].ToString());
//TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
//textBox5.Text = string.Empty;
//textBox7.Text = string.Empty;
// *****textBox8.Text = Session["id"] + "";
}
else
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + textBox1.Text + "'", con1);
SqlCommand myCommand = new SqlCommand("select u.user_id, u.user_fname, u.user_lname, c.user_id, c.card_balance,c.card_id from [user] u JOIN [card] c ON u.user_id = c.user_id where c.user_id = '" + textBox1.Text + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
textBox6.Text = (myReader["card_balance"].ToString());
textBox2.Text = (myReader["user_fname"].ToString());
textBox3.Text = (myReader["user_lname"].ToString());
textBoxcardid.Text = (myReader["card_id"].ToString());
}
con1.Close();
textBox5.Text = string.Empty;
textBox7.Text = string.Empty;
label9.Text = string.Empty;
// ****textBox8.Text = Session["id"] + "";
}//end using
}
}
private void button3_Click(object sender, EventArgs e)
{
textBox7.Text = (Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text)).ToString();
using (SqlConnection con1 = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
if (textBox1.Text.Contains("g") || textBox1.Text.Contains("G") == true)
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + TextBox1.Text + "'", con1);
SqlCommand myCommand = new SqlCommand("UPDATE card c join guest g on c.guest_id = g.guest_id SET c.card_balance = #card_balance,g.guest_status=#guest_status WHERE c.guest_id = '" + textBox1.Text + "'", con1);
myCommand.Parameters.Add("#card_balance", System.Data.SqlDbType.SmallInt);
//myCommand.Parameters.Add("#staff_id", System.Data.SqlDbType.SmallInt);
myCommand.Parameters["#card_balance"].Value = textBox7.Text;
//myCommand.Parameters["#staff_id"].Value = textBox8.Text;
myCommand.Parameters.AddWithValue("#guest_status", textBox9.Text);
//myCommand.Parameters["#staff_id"].Value = Session["];
try
{
myCommand.ExecuteNonQuery();
//TextBox1.Text = string.Empty;
//TextBox2.Text = string.Empty;
//TextBox3.Text = string.Empty;
//TextBox5.Text = string.Empty;
//TextBox6.Text = string.Empty;
using (SqlConnection conn = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
SqlCommand cmd = new SqlCommand("INSERT INTO transactionc (tranc_total, card_id,staff_id,date) VALUES (#tranc_total, #staff_id,#card_id, #date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#tranc_total", textBox5.Text);
cmd.Parameters.AddWithValue("#card_id", textBoxcardid.Text);
cmd.Parameters.AddWithValue("#staff_id",textBox8.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
//cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
label9.Text = "<b><big><big> Complete !!!</big></big> </b>";
}
catch
{
textBox7.Text = string.Empty;
label9.Text = "<b> <big> <big> Not Complete!!!</big> </big> </b>";
}
finally
{
con1.Close();
}
//myCommand.Parameters.AddWithValue("#card_balance", TextBox7.Text);
//myCommand.ExecuteNonQuery();
}
else
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
//SqlCommand myCommand = new SqlCommand("select * from card,user where card.card_id='" + TextBox1.Text + "'", con1);
SqlCommand myCommand = new SqlCommand("UPDATE card set card_balance=#card_balance , WHERE user_id = '" + textBox1.Text + "'", con1);
myCommand.Parameters.Add("#card_balance", System.Data.SqlDbType.SmallInt);
//myCommand.Parameters.Add("#staff_id", System.Data.SqlDbType.SmallInt);
myCommand.Parameters["#card_balance"].Value = textBox7.Text;
//myCommand.Parameters["#staff_id"].Value = textBox8.Text;
//myCommand.Parameters.AddWithValue("#guest_status", TextBox9.Text);
//myCommand.Parameters["#staff_id"].Value = Session["];
try
{
myCommand.ExecuteNonQuery();
//TextBox1.Text = string.Empty;
//TextBox2.Text = string.Empty;
//TextBox3.Text = string.Empty;
//TextBox5.Text = string.Empty;
//TextBox6.Text = string.Empty;
using (SqlConnection conn = new SqlConnection("Data Source=KHUNP\\SQLEXPRESS;Initial Catalog=kmuttssc;User ID=sa;Password=db2admin;"))
{
SqlCommand cmd = new SqlCommand("INSERT INTO transactionc (tranc_total, card_id,staff_id, date) VALUES (#tranc_total, #card_id,#staff_id, #date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#tranc_total", textBox5.Text);
cmd.Parameters.AddWithValue("#card_id", textBoxcardid.Text);
cmd.Parameters.AddWithValue("#staff_id", textBox8.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
//cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
label9.Text = "<b><big><big> Complete !!!</big></big> </b>";
}
catch
{
textBox7.Text = string.Empty;
label9.Text = "<b> <big> <big> Not Complete!!!</big> </big> </b>";
}
finally
{
con1.Close();
}
}
}
}
private void button5_Click(object sender, EventArgs e)
{
Form targetform = new Return(s, r);
targetform.Show();
this.Hide();
}
private void button6_Click(object sender, EventArgs e)
{
Form targetform = new Home1(s, r);
targetform.Show();
this.Hide();
}
}
}
I think you need to provide permission to your user. Go to your database and execute the below query:-
USE [DBName]
GO
EXEC sp_addrolemember N'db_datawriter', N'UserName'
GO
EXEC sp_addrolemember N'db_datareader', N'UserName'
There is one more approach to give the permsion which is by using the GRANT privilage.

how to retrieve integer value from database & store it in integer in .net

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
d = dr[0].ToString();
//d =(string) Label4.Text;
con.Close();
}
I want integer value from database
try
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
con.Close();
dr.GetInt32(0) should read an int at position 0
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
d = GetYear(cmd).ToString();
con.Close();
}
the "dirty" work is done by GetYear :
private const DEFAULT_YEAR = 2000;
private int GetYear(System.Data.IDbCommand command) {
int year = DEFAULT_YEAR;
using (System.Data.IDataReader reader = command.ExecuteReader()) {
if (reader.Read()) {
year = GetIntOrDefault(reader, 0);
}
}
return year;
}
private int GetIntOrDefault(System.Data.IDataRecord record, int ordinal) {
if (record.IsDBNull(ordinal)) {
return DEFAULT_YEAR;
} else {
return record.GetInt32(ordinal);
}
}
string InvAmountQuery = "SELECT InvAmount FROM Registration WHERE Email='" + useremail + "' ";
SqlCommand InvAmountcom = new SqlCommand(InvAmountQuery, conn);
int InvAmount = Convert.ToInt32(InvAmountcom.ExecuteScalar().ToString());

Inserting and Updating data to MDB

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.

Categories