您的位置:首页 > 数据库

ADO.NET之4-使用SqlCommand对象向数据库添加记录---ShinePans

2014-08-02 13:46 609 查看
源代码:

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();
}
}
}


数据库设计:



运行:



运行之后的数据库状态:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ado.net