using System; using System.Configuration; using System.Data.SqlClient; using MessageBoxer; namespace ConnectDatabaseDemo { /// <summary> /// 各种数据库连接字符串写法:https://www.connectionstrings.com/ /// LDH @ 2021-4-8 /// ADO.NET访问数据库方法总结 /// </summary> internal class Program { private static void Main() { Console.Title = "使用ADO.NET连接数据库"; //ConnectDbMethod01(); ConnectDbMethod02(); } /// <summary> /// 连接数据库方法1:将数据库连接字符串配置到App.config文件内,connectionStrings节点下 /// </summary> private static void ConnectDbMethod01() { var conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); var con = new SqlConnection(conStr); try { con.Open(); ShowMessage.Notification("已打开数据库连接!", "温馨提示"); } catch (Exception e) { ShowMessage.Error(e.Message, "异常提示"); } finally { con.Close(); ShowMessage.Notification("已关闭数据库连接!", "温馨提示"); } } /// <summary> /// 连接数据库方法2:将数据库连接字符串配置到App.config文件内,appSettings节点下 /// </summary> private static void ConnectDbMethod02() { var conStr = ConfigurationManager.AppSettings["ConnectionString"]; using (var con = new SqlConnection(conStr)) { try { con.Open(); ShowMessage.Notification("已打开数据库连接!", "温馨提示"); } catch (Exception e) { ShowMessage.Error(e.Message, "异常提示"); } } } } }
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <!--配置数据库连接字符串--> <connectionStrings> <!--写法1--> <add name="ConnectionString" connectionString="Data Source=localhost;Initial Catalog=TestDB;User Id=sa;Password=123456"/> <!--<add name="ConnectionString" connectionString="Data Source=.;Initial Catalog=TestDB;User Id=sa;Password=123456"/>--> <!--<add name="ConnectionString" connectionString="Data Source=127.0.0.1;Initial Catalog=TestDB;User Id=sa;Password=123456"/>--> <!--写法2--> <!--<add name="ConnectionString" connectionString="server=.;database=TestDB;uid=sa;pwd=123456"/>--> <!--<add name="ConnectionString" connectionString="server=localhost;database=TestDB;uid=sa;pwd=123456"/>--> <!--<add name="ConnectionString" connectionString="server=127.0.0.1;database=TestDB;uid=sa;pwd=123456" />--> </connectionStrings> <!--配置数据库连接字符串 方式1 ↑--> <!--配置数据库连接字符串--> <appSettings> <add key="ConnectionString" value="Data Source=localhost;Initial Catalog=TestDB;User Id=sa;Password=123456" /> </appSettings> <!--配置数据库连接字符串 方式2 ↑--> </configuration>
/* 日期:2021-4-8 人员:LDH 说明:SQL-简单创建数据库和表 */ IF EXISTS (SELECT * FROM sys.databases WHERE name = 'TestDB') DROP DATABASE TestDB; GO CREATE DATABASE TestDB; GO USE TestDB; GO CREATE TABLE Students ( Id INT IDENTITY(1, 1) PRIMARY KEY NOT NULL, Name NVARCHAR(20) NOT NULL, Age INT NOT NULL CHECK (Age BETWEEN 1 AND 150 ) DEFAULT 1, Address NVARCHAR(200) NOT NULL DEFAULT '地址不详' ); INSERT INTO dbo.Students ( Name, Age, Address ) VALUES ( N'LDH', -- Name - nvarchar(20) 32, -- Age - int N'中国上海' -- Address - nvarchar(200) ); SELECT Id, Name, Age, Address FROM dbo.Students;