码迷,mamicode.com
首页 > 数据库 > 详细

C#: DataBase

时间:2016-12-26 00:47:26      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:time   状态   str   open   source   tar   users   sla   delete   


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

C#: DataBase

标签:time   状态   str   open   source   tar   users   sla   delete   

原文地址:http://www.cnblogs.com/adelaide/p/6220732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!