C#: DataBase


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;
}
}
}

转载于:https://www.cnblogs.com/adelaide/p/6220732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值