C# 使用sqlserver2000

来源:互联网 发布:奥运会排球编程表 编辑:程序博客网 时间:2024/05/21 15:48

using System.Data.SqlClient;
建立连接
SqlConnection myConnection = new SqlConnection("数据库连接字符串");
数据库连接字符串通常是:Data Source=localhost;Initial Catalog=数据库名;User ID=用户名;Password=密码
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "select count(*) from 要查询的表名 where 查询的字段名= '"+保存查询值的变量名+"'";
myCommand.Connection = myConnection;

try
{
myCommand.Connection.Open();
int count = (int)myCommand.ExecuteScalar();
if (count > 0)
{
count大于0表示有,调用自己写的一个方法来更新
UpdateData();

}
else
{
小于0表示没有,调用这个方法来插入
InsertData();
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
UpdateData方法
public void UpdateData()
{
SqlConnection myConnection = new SqlConnection("数据库连接字符串");
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "用来更新的SQL语句";
myCommand.Connection = myConnection;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

InsertData方法
public void InsertData()
{
SqlConnection myConnection = new SqlConnection("数据库连接字符串");
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "用来插入的SQL语句";
myCommand.Connection = myConnection;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

原创粉丝点击