38.连接数据库和断开数据库
有两种办法连接数据库,一种是利用向导,就不做介绍了。另外就是利用代码,sql的Connetion类。
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.SqlClient;
namespace WindowsFormsApplication33
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CreateSqlConnection();
}
public void CreateSqlConnection()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source = (local); DataBase = master; Integrated Security = true";
try
{
conn.Open();
}
catch(SqlException e)
{
MessageBox.Show(e.ToString());
}
this.toolStripStatusLabel1.Text = "连接数据库状态为:" + conn.State.ToString();
}
}
}
断开数据库的连接,conn。Close()方法。
本文出自 “郭俊的博客” 博客,转载请与作者联系!
原文地址:http://10093949.blog.51cto.com/10083949/1633047