seo网站首页优化排名怎么做,唐山营销型网站建设,怎么做百度里面自己的网站,优化营商环境个人心得体会文章目录 环境搭建数据库关键修改说明#xff1a;在代码中使用该连接字符串#xff1a;注意事项#xff1a;实际使用 都说几天创造一个奇迹#xff0c;现在是真的这样了#xff0c;Just do it!
环境搭建
数据库
需要下载这个SQL Server数据库#xff0c;然后每次Visua… 文章目录 环境搭建数据库关键修改说明在代码中使用该连接字符串注意事项实际使用 都说几天创造一个奇迹现在是真的这样了Just do it!
环境搭建
数据库
需要下载这个SQL Server数据库然后每次Visual Studio连接的时候需要我们本地就运行这个SQL Server 视图-SQL Server 对象资源管理器 对于你想要连接的数据库属性-连接字符串 然后就是去配置App.config文件
需要在现有的 app.config 文件中添加数据库连接字符串。以下是修改后的完整配置文件内容
?xml version1.0 encodingutf-8 ?
configurationstartup supportedRuntime versionv4.0 sku.NETFramework,Versionv4.7.2 //startupconnectionStringsadd nameFruitAppConnection connectionStringData SourceGWJ;Initial Catalogfruitapp;Integrated SecurityTrue;Connect Timeout30;EncryptFalse;Trust Server CertificateTrue;Application IntentReadWrite;Multi Subnet FailoverFalse providerNameSystem.Data.SqlClient //connectionStrings
/configuration关键修改说明 添加 connectionStrings 节点 在 configuration 节点下新增该节点用于存放数据库连接信息。 配置连接字符串 nameFruitAppConnection自定义连接字符串的名称在代码中通过此名称引用。connectionString使用你提供的完整连接字符串。providerNameSystem.Data.SqlClient指定使用 SQL Server 数据提供程序。
在代码中使用该连接字符串
在 C# 代码中可以通过以下方式获取并使用这个连接字符串
using System.Configuration; // 需要添加对 System.Configuration 的引用// 获取连接字符串
string connStr ConfigurationManager.ConnectionStrings[FruitAppConnection].ConnectionString;// 使用 SqlSugar 示例
var db new SqlSugarClient(new ConnectionConfig
{ConnectionString connStr,DbType DbType.SqlServer,IsAutoCloseConnection true
});注意事项
确保 SQL Server 实例名称Data SourceGWJ与你本地环境一致。如果使用 Windows 身份验证Integrated SecurityTrue确保运行程序的用户账户有权限访问 fruitapp 数据库。如果数据库需要特殊权限可改用 SQL Server 身份验证添加 User ID 和 Password 参数。
实际使用
实际上我们在具体的.cs文件对于数据库进行操作的时候还需要引入这个System.Data.SqlClient命名空间以便使用SQL Server数据库连接和操作的相关类
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;namespace appfruit
{public partial class LoginForm : Form{public LoginForm(){InitializeComponent();}private void btnLogin_Click(object sender, EventArgs e){string username txtUsername.Text;string password txtPassword.Text;// 从 App.config 中读取数据库连接字符串string connectionString ConfigurationManager.ConnectionStrings[FruitAppConnection].ConnectionString;using (SqlConnection connection new SqlConnection(connectionString)){try{// 打开数据库连接connection.Open();// 编写 SQL 查询语句假设用户信息存储在名为 Users 的表中string query SELECT COUNT(*) FROM Users WHERE Username Username AND Password Password;SqlCommand command new SqlCommand(query, connection);command.Parameters.AddWithValue(Username, username);command.Parameters.AddWithValue(Password, password);// 执行查询并获取结果int count (int)command.ExecuteScalar();if (count 0){MessageBox.Show(登录成功);this.DialogResult DialogResult.OK;this.Close();}else{MessageBox.Show(用户名或密码错误请重试。);}}catch (Exception ex){MessageBox.Show(数据库连接或查询出错 ex.Message);}}}}
}