ADO.NET之4-使用SqlCommand对象向数据库添加记录---ShinePans,
源代码:
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();
sc.ConnectionString = connection;
try
{
sc.Open(); //打开数据库连接
Console.WriteLine("已经打开数据库连接!");
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("添加记录成功"); //控制台输出添加记录
}
catch (Exception ex)
{
Console.WriteLine("打开数据库错误:{0}", ex.Message);
}
finally
{
sc.Close();
Console.WriteLine("数据库连接已关闭!");
}
System.Console.ReadLine();
}
}
}
数据库设计:
运行:
运行之后的数据库状态:
1.创建数据库连接字符创
2.导入命名空间System.data.sqlcen...
3.jia创建SQLCONNECTION 对象 把链接字符创 放进去
4. 打开数据库
5.声明SQLcommand对象 括号内放 执行命令的SQL语句 和connection对象
6command对象。方法执行相关命令
using System.Data;
using System.Data.SqlClient;
..
string strConnection="user id=sa;password=;";
strConnection+="initial catalog=Northwind;Server=YourSQLServer;";
strConnection+="Connect Timeout=30";
SqlConnection objConnection=new SqlConnection(strConnection);
..
objConnection.Open();
objConnection.Close();
strConnection这个变量里存放的是连接数据库所需要的连接字符串,他指定了要使用的数据提供者和要使用的数据源.
首先,连接SQL Server使用的命名空间是"System.Data.SqlClient".
其次就是他的连接字符串了,我们一个一个参数来介绍(注意:参数间用分号分隔):
"user id=sa":连接数据库的验证用户名为sa.他还有一个别名"uid",所以这句我们还可以写成"uid=sa".
"password=":连接数据库的验证密码为空.他的别名为"pwd",所以我们可以写为"pwd=".
这里注意,你的SQL Server必须已经设置了需要用户名和密码来登录,否则不能用这样的方式来登录.如果你的SQL Server设置为Windows登录,那么在这里就不需要使用"user id"和"password"这样的方式来登录,而需要使用"Trusted_Connection=SSPI"来进行登录.
"initial catalog=Northwind":使用的数据源为"Northwind"这个数据库.他的别名为"Database",本句可以写成"Database=Northwind".
"Server=YourSQLServer":使用名为"YourSQLServer"的服务器.他的别名为"Data Source","Address","Addr".如果使用的是本地数据库且定义了实例名,则可以写为"Server=(local)/实例名";如果是远程服务器,则将"(local)"替换为远程服务器的名称或IP地址.
"Connect Timeout=30":连接超时时间为30秒.
在这里,建立连接对象用的构造函数为:SqlConnection.