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 = "状态:已覆盖原数据";
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 = "状态:录入完成";
}
}
//
// search
//
public void GetData(Form1 obj)
{
string id = obj.idTextBox.Text;
SelectData(id);
//最后让label显示检索到的字段的值.
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 = "未查询到该商品";
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 = "状态:查询完成";
Goods.exist = true;
}
con.Close();
}
public bool exist(string id)
{
Goods.exist = false;
SelectData(id);
return Goods.exist;
}
}
}