//连接数据库
string SQLCONNECT = @"server=PC-200907281720\SQLEXPRESS;database=master;uid=morewindows;pwd=12345";
SqlConnection conn = new SqlConnection(SQLCONNECT);
conn.Open();
//连接数据库之后就可以执行SQL命令了
//使用SqlCommand类的ExecuteReader()返回执行的结果
string SQLCOMMAND = "select CName, names, C4.LastLogin from C4, S4 where C4.LastLogin = S4.LastLogin order by CName, names";
SqlCommand sqlcmd = new SqlCommand(SQLCOMMAND, conn);
SqlDataReader sr = sqlcmd.ExecuteReader();
Console.WriteLine("列数:" + sr.FieldCount);
Console.WriteLine("列类型分别为:");
int nSqlCol = sr.FieldCount;
for (int i = 0; i < nSqlCol; ++i)
Console.Write(sr.GetFieldType(i) + " ");
Console.WriteLine();
while (sr.Read())
{
for (int i = 0; i < nSqlCol; i++)
Console.Write(sr[i].ToString() + " ");
Console.WriteLine();
}
sr.Close();
//通过SqlCommand 类的ExecuteNonQuery()来返回受影响的行数。
string SQLCOMMAND2 = "update dbo.Messages set MessageNum='15' where MessageID='2'";
SqlCommand sqlcmd2 = new SqlCommand(SQLCOMMAND2, conn);//也可以用sqlcmd. ConnectionString = SQLCOMMAND2 代替
int nResult = sqlcmd2.ExecuteNonQuery();
Console.WriteLine("受影响行数:" + nResult);
conn.Close();
C#访问数据库
最新推荐文章于 2024-08-26 11:12:08 发布