C#数据库连接
1. mysql的数据库连接
step1:首先需要在代码中添加Mysql.Data的代码依赖。如果添加失败则需要去搜索下载安装!如下图:
代码导入
using MySql.Data.MySqlClient;
step2:建立连接
//设置连接基本参数
string connStr = "server = localhost; user = root; database = world; port = 3306; password = ***"
//使用MysqlConnection 创建连接
MySqlConnection conn = new MySqlConnection(connStr) ;
//开启连接
try{conn.Open();}
catch(Exception ex){Console.WriteLine(ex.ToString());}step3:读取数据
//生成命令。
string sqlStr = "select * from 测试 where 性别 = @sex"; //和下文的"@sex"对应。
MySqlCommand cmd = new MySqlCommand(sqlStr, conn); //生成命令构造器对象。
cmd.Parameters.AddWithValue("@sex", textBox_sex.Text);
//查询结果。
MySqlDataReader rdr = cmd.ExecuteReader();
try
{
while (rdr.Read())//Read()函数设计的时候是按行查询,查完一行换下一行。
{
string s1 = rdr[0].ToString();
string s2 = rdr[1].ToString();
}
}catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "错误信息");
}
2.sqlserver 的数据库连接
step1:同样需要导入包:using System.Data.SqlClient; 没有同上操作去下载安装。
sqlserver 建立连接代码:
/*
* Data Source = 服务器名
* Initial Catalog = 数据库名
* User ID = 用户名
* Pwd = 密码(没有密码可以省略)
* Integrated Security = TRUE(或者:SSPI) ---选择用户密码或者这个连接数据库
*/
string str = "Data Source = DESKTOP-JA3IJMB; Initial Catalog = BookDB; Integrated Security = TRUE";
con = new SqlConnection(str);
con.Open();//打开数据库step2:读取数据和mysql类似就不再讲解,下面粘贴一个处理数据库连接的简单版包装类。
using System;
using System.Data.SqlClient;
namespace LoginWin
{
//数据库操作
class Dao
{
SqlConnection con = null;
public SqlConnection connect ()
{
/*
* Data Source = 服务器名
* Initial Catalog = 数据库名
* User ID = 用户名
* Pwd = 密码(没有密码可以省略)
* Integrated Security = TRUE(或者:SSPI) ---选择用户密码或者这个连接数据库
*/
string str = "Data Source = DESKTOP-JA3IJMB; Initial Catalog = BookDB; Integrated Security = TRUE";
con = new SqlConnection(str);
con.Open();//打开数据库
return con;
}
public SqlCommand Command(string sql)
{
SqlCommand cmd = new SqlCommand(sql,connect());
return cmd;
}
public int Execute(string sql)
{
//更新操作
return Command(sql).ExecuteNonQuery();
}
public SqlDataReader read(string sql)
{
//读取操作
return Command(sql).ExecuteReader();
}
public void Colse()
{
con.Close();
}
}
}



浙公网安备 33010602011771号