时间:2021-07-01 10:21:17 帮助过:24人阅读
查询数据路里的数据数量: 代码: using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SQLTest{ class Program { static void Main(
查询数据路里的数据数量:
代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLTest
{
class Program
{
static void Main(string[] args)
{
///连接数据库
string connection =
"server=潘尚\\SQLEXPRESS;database=db_test;Trusted_Connection=true";
SqlConnection sc = new SqlConnection(connection);
sc.ConnectionString = connection;
try
{
sc.Open(); //打开数据库连接
Console.WriteLine("已经打开数据库连接!");
SqlCommand cmd = new SqlCommand("SELECT count(*) FROM db_student", sc);
int i = (int)cmd.ExecuteScalar();//执行查找记录的命令
Console.WriteLine("表中共有{0}条数据", i.ToString());
//START:3.修改数据库数据的代码////////////////////////////////////////////////////////
/* SqlCommand cmd = new SqlCommand("UPDATE db_student SET student_grade=99 where student_name=@name", sc); //创建SqlCommand对象
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = "潘";
int i = cmd.ExecuteNonQuery();
if (i > 0) Console.WriteLine("修改成功!"); */
//END:3.修改数据库数据的代码/////////////////////////////////////////////////////////
//START:1.删除数据库记录代码段///////////////////////////////////////////////////////
/* string cmdtext = "DELETE FROM db_student WHERE student_name=@name";
SqlCommand cmd = new SqlCommand(cmdtext, sc);
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = "潘";
int i = cmd.ExecuteNonQuery();
if (i > 0) Console.WriteLine("删除记录成功!"); */
//END:1.删除数据库记录代码段/////////////////////////////////////////////////////////
//START:2.添加记录的代码///////////////////////////////////////////////////////////////
/* SqlCommand cmd = new SqlCommand();//创建SqlCommand对象
cmd.CommandType = CommandType.Text; //设置执行文本命令
cmd.Connection = sc; //设置对象属性
cmd.CommandText =
"INSERT INTO db_student(student_name,student_age,student_address,student_grade)VALUES(@name,@age,@address,@grade)";
//添加参数并为参数赋值
cmd.Parameters.Add("@name", SqlDbType.VarChar, 10).Value = "潘";
cmd.Parameters.Add("@age", SqlDbType.Int).Value = 19;
cmd.Parameters.Add("@address", SqlDbType.VarChar).Value = "武汉";
cmd.Parameters.Add("@grade", SqlDbType.Int).Value = 100;
int i = cmd.ExecuteNonQuery(); //执行数据库添加记录命令
if (i > 0) Console.WriteLine("添加记录成功"); */ //控制台输出添加记录
//END:2.添加记录的代码/////////////////////////////////////////////////////////////////
}
catch (Exception ex)
{
Console.WriteLine("打开数据库错误:{0}", ex.Message);
}
finally
{
sc.Close();
Console.WriteLine("数据库连接已关闭!");
}
System.Console.ReadLine();
}
}
}
运行结果:
