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());
}
}
这篇博客演示了如何使用C#与SQL Server 2000进行交互,包括建立数据库连接,执行查询语句以检查数据存在与否,并根据查询结果调用UpdateData()或InsertData()方法进行数据更新或插入操作。在遇到异常时,程序会捕获并显示异常信息。
1399

被折叠的 条评论
为什么被折叠?



