最近在學習C#開發,需要連接資料庫,做一個簡單的測驗,點擊按鈕,就會把對應資料庫中的表顯示到DataGridView中,然后網上復制一段代碼,進行了必要的修改,運行沒有報錯,就是點擊按鈕沒有任何反應,求大神幫忙
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using MySQLDriverCS;
namespace DbTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strConn = "server=localhost;uid=root;password=;Database=test;Charset=utf8";
MySqlConnection conn = new MySqlConnection(strConn);
conn.Open();//鏈接資料庫
try
{
conn.Open();
conn.Close();
MessageBox.Show("資料庫連接成功!");
}
catch (Exception)
{
MessageBox.Show("連接資料庫失敗!");
}
DataSet ds = new DataSet();
string sql = "select * from student";
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds, "table");
dataGridView1.DataSource = ds.Tables["table"];
}
}
}
uj5u.com熱心網友回復:
try
{
conn.Open();
conn.Close();
MessageBox.Show("資料庫連接成功!");
}
catch (Exception)
{
MessageBox.Show("連接資料庫失敗!");
}
open是打開連接,close是關閉連接。 這個連接剛打開就被你關了。應該把close這句放到資料庫讀寫完畢之后
uj5u.com熱心網友回復:
應該和這沒關系,我試過了,還是沒有用,很郁悶呢,明明沒有報錯uj5u.com熱心網友回復:
應該和這個沒有關系,我試過了,還是不行
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/62451.html
上一篇:SStab中選項卡間資料的呼叫
