建议配合使用:如何下载和安装sql server数据库-csdn博客
1. 引入必要的命名空间
若要连接 sql server 数据库,需引入system.data.sqlclient
命名空间。
2. 构建数据库连接字符串
连接字符串包含数据库服务器地址、数据库名称、认证方式等连接所需信息。
就是这张图片的内容,里面的连接字符串
下面是几种常见的连接字符串示例:
示例 1:使用 windows 身份验证
string connectionstring = "data source=服务器名;initial catalog=数据库名;integrated security=true";
示例 2:使用 sql server 身份验证
要选择混合验证,不然无法使用sql server 身份验证,根据自己的设置输入
string connectionstring = "data source=服务器名;initial catalog=数据库名;user id=用户名;password=密码";
3. 连接数据库并执行 sql 命令
可以借助sqlconnection
和sqlcommand
对象来连接数据库并执行 sql 命令。以下是一个完整的示例:
using system; using system.data.sqlclient; class program { static void main() { // 定义连接字符串 string connectionstring = "data source=localhost;initial catalog=northwind;integrated security=true"; try { // 创建并打开数据库连接 using (sqlconnection connection = new sqlconnection(connectionstring)) { connection.open(); console.writeline("数据库连接成功!"); // 定义sql查询命令 string sql = "select customerid, companyname from customers"; // 创建sqlcommand对象 using (sqlcommand command = new sqlcommand(sql, connection)) { // 执行查询并获取数据读取器 using (sqldatareader reader = command.executereader()) { // 读取查询结果 while (reader.read()) { console.writeline($"客户id: {reader["customerid"]}, 公司名称: {reader["companyname"]}"); } } // 执行插入命令示例 string insertsql = "insert into products (productname, unitprice) values (@productname, @unitprice)"; using (sqlcommand insertcommand = new sqlcommand(insertsql, connection)) { // 添加参数以防止sql注入 insertcommand.parameters.addwithvalue("@productname", "新产品"); insertcommand.parameters.addwithvalue("@unitprice", 9.99); // 执行非查询命令(如insert、update、delete) int rowsaffected = insertcommand.executenonquery(); console.writeline($"插入了{rowsaffected}行数据。"); } } } } catch (exception ex) { console.writeline("数据库操作出错: " + ex.message); } } }
4. 关键步骤说明
创建连接对象:通过
sqlconnection
类创建数据库连接对象,构造函数的参数为连接字符串。打开连接:调用
open()
方法开启数据库连接,此操作应包含在try-catch
块中,以便捕获可能出现的异常。执行命令:利用
sqlcommand
类执行 sql 命令,可通过executereader()
方法执行查询命令,获取查询结果;也可使用executenonquery()
方法执行插入、更新、删除等操作。关闭连接:使用
using
语句能确保连接资源被正确释放,无需手动调用close()
或dispose()
方法。
5. 其他注意事项
参数化查询:在 sql 命令中使用参数(如
@parametername
),可以有效防止 sql 注入攻击。异常处理:数据库操作可能会因为网络问题、权限不足等原因失败,所以必须进行异常处理。
连接池:.net 会自动管理连接池,一般情况下无需手动配置。
到此这篇关于c#连接sql server数据库命令的基本步骤的文章就介绍到这了,更多相关c#连接sql server数据库内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论