Using System.Data.SqlClient;
Namespace WindowsFormsApplication1
{
Class DB
{
Private SqlConnection con;
Private SqlCommand cmd;
private string ConnectionString = "Data source= (LocalDB) \\MSSQLLocalDB; Attachdbfilename=c:\\users\\ramon\\documents\\visual Studio 2015\\projects\\windowsformsapplication1\\ Windowsformsapplication1\\mytest.mdf;integrated security=true; Connect timeout=30 ";
Public DB ()
{
}
//
Insert
//
public void InsertData (Form1 obj)
{
string id = obj.idTextBox.Text;
BOOL cover = false;;
if (exist (ID))
{
DeleteRow (ID);
Obj.statusLabel.Text = "Status: The original data has been overwritten";
Cover = true;
}
This.con = new SqlConnection ();
Con. ConnectionString = ConnectionString;
Con. Open ();
cmd = new SqlCommand ("INSERT into Goods (id,name,num,price) VALUES (@Id, @Name, @Num, @Price)", con);
cmd = new SqlCommand ("INSERT into Goods (id,name,num,price) VALUES (2,12,123,1234)", con);
Cmd. Parameters.addwithvalue ("@Id", Obj.idTextBox.Text);
Cmd. Parameters.addwithvalue ("@Name", Obj.nameTextBox.Text);
Cmd. Parameters.addwithvalue ("@Num", Obj.numTextBox.Text);
Cmd. Parameters.addwithvalue ("@Price", Obj.priceTextBox.Text);
Cmd. ExecuteNonQuery ();
Con. Close ();
if (!cover) {
Obj.statusLabel.Text = "Status: Input Complete";
}
}
//
Search
//
public void GetData (Form1 obj)
{
string id = obj.idTextBox.Text;
Selectdata (ID);
Finally, let the label display the value of the retrieved field.
Obj.nameTextBox.Text = Goods.name;
Obj.numTextBox.Text = Goods.num;
Obj.priceTextBox.Text = Goods.price;
Obj.statusLabel.Text = Goods.status;
if (! Goods.exist)
{
Obj.statusLabel.Text = "The product has not been queried";
Obj.nameTextBox.Text = "";
Obj.numTextBox.Text = "";
Obj.priceTextBox.Text = "";
}
}
public void DeleteRow (string id)
{
This.con = new SqlConnection ();
Con. ConnectionString = ConnectionString;
Con. Open ();
String cmdtext = "Delete from Goods WHERE id= '" + Id + "'";
cmd = new SqlCommand (Cmdtext, con);
SqlDataReader reader = cmd. ExecuteReader ();
}
public void Selectdata (string id)
{
This.con = new SqlConnection ();
Con. ConnectionString = ConnectionString;
Con. Open ();
String cmdtext = "SELECT * from Goods WHERE id= '" + Id + "'";
cmd = new SqlCommand (Cmdtext, con);
SqlDataReader reader = cmd. ExecuteReader ();
while (reader. Read ())
{
Goods.name = reader["Name"]. ToString ();
Goods.num = reader["num"]. ToString ();
Goods.price = reader["Price"]. ToString ();
Goods.status = "Status: Query Complete";
Goods.exist = true;
}
Con. Close ();
}
public bool exist (string ID)
{
Goods.exist = false;
Selectdata (ID);
return goods.exist;
}
}
}
C #: DataBase