C#窗体——VS2019连接到Navicat的sqlServer数据库
1、搭建一个特别简单的窗体
简单且丑陋~
2、代码编写
新建一个DataBase.cs的类:
写入代码:
//DataBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace SQLServerTest
{
class DataBase
{
public SqlConnection getConn()
{
string strConn = "server=localhost;database=test1007;uid=1007;pwd=123456";
SqlConnection sqlConnection = new SqlConnection(strConn);
return sqlConnection;
}
}
}
//Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace SQLServerTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//查询数据库信息
private void button1_Click(object sender, EventArgs e)
{
//获取数据库连接
DataBase dataBase = new DataBase();
SqlConnection sqlConnection = dataBase.getConn();
//打开连接
sqlConnection.Open();
//定义sql语句
string sql = "select * from testTable";
//执行sqlCommand对象
SqlCommand sqlCommand = new SqlCommand(sql,sqlConnection);
//创建数据适配器
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
//执行sql语句
sqlDataAdapter.SelectCommand = sqlCommand;
//创建数据集
DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet,"testTable");
dataGridView1.DataSource = dataSet.Tables[0];
//关闭连接
sqlConnection.Close();
}
}
}
需要先将这两个using块引用进去:
然后点击查询就显示出来数据啦!(从未见过如此丑陋的操作)
OK!