public
class
DBPerson
{
///
<summary>
///
插入操作
///
</summary>
public
void
Create(Person person)
{
string
sql
=
"
insert into UserInfo(UserName,Password,Age) values (@UserName,@Password,@Age)
"
;
SqlConnection conn
=
Connection.GetConnection();
SqlCommand command
=
new
SqlCommand(sql, conn);
//
定义参数,插值
command.Parameters.Add(
new
SqlParameter(
"
@UserName
"
, SqlDbType.VarChar));
command.Parameters.Add(
new
SqlParameter(
"
@Password
"
, SqlDbType.VarChar));
command.Parameters.Add(
new
SqlParameter(
"
@Age
"
, SqlDbType.Int));
command.Parameters[
"
@UserName
"
].Value
=
person.UserName;
command.Parameters[
"
@Password
"
].Value
=
person.Pwd;
command.Parameters[
"
@Age
"
].Value
=
person.Age;
try
{
command.ExecuteNonQuery();
}
catch
(System.Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
//不要忘记将数据库关闭
conn.Close();
}
}
///
<summary>
///
修改操作
///
</summary>
public
void
Update(Person person)
{
string
sql
=
"
update UserInfo set UserName=@UserName,Password=@Password,Age=@Age where ID=@ID
"
;
SqlConnection conn
=
Connection.GetConnection();
SqlCommand command
=
new
SqlCommand(sql, conn);
command.Parameters.Add(
new
SqlParameter(
"
@UserName
"
, SqlDbType.VarChar));
command.Parameters.Add(
new
SqlParameter(
"
@Password
"
, SqlDbType.VarChar));
command.Parameters.Add(
new
SqlParameter(
"
@Age
"
, SqlDbType.Int));
command.Parameters.Add(
new
SqlParameter(
"
@ID
"
, SqlDbType.Int));
command.Parameters[
"
@UserName
"
].Value
=
person.UserName;
command.Parameters[
"
@Password
"
].Value
=
person.Pwd;
command.Parameters[
"
@Age
"
].Value
=
person.Age;
command.Parameters[
"
@ID
"
].Value
=
person.ID;
try
{
command.ExecuteNonQuery();
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
finally
{
conn.Close();
}
}
///
<summary>
///
查看操作
///
</summary>
public
Person GetById(
int
id)
{
string
sql
=
"
select * From UserInfo where ID = @ID
"
;
SqlConnection conn
=
Connection.GetConnection();
SqlCommand command
=
new
SqlCommand(sql, conn);
command.Parameters.Add(
new
SqlParameter(
"
@ID
"
, SqlDbType.Int));
command.Parameters[
"
@ID
"
].Value
=
id;
SqlDataReader reader
=
command.ExecuteReader();
Person person
=
null
;
if
(reader.Read())
{
person
=
new
Person();
person.ID
=
id;
person.UserName
=
reader[
"
UserName
"
].ToString();
person.Pwd
=
reader[
"
Password
"
].ToString();
person.Age
=
Convert.ToInt32(reader[
"
Age
"
]);
}
reader.Close();
conn.Close();
return
person;
}
///
<summary>
///
删除操作
///
</summary>
public
void
RemoveById(
int
id)
{
string
sql
=
"
delete from UserInfo where ID = @ID
"
;
SqlConnection conn
=
Connection.GetConnection();
SqlCommand command
=
new
SqlCommand(sql, conn);
command.Parameters.Add(
new
SqlParameter(
"
@ID
"
, SqlDbType.Int));
command.Parameters[
"
@ID
"
].Value
=
id;
try
{
command.ExecuteNonQuery();
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
}
}