折騰了好久,蒙圈了很久,終于調(diào)用數(shù)據(jù)庫(kù)成功,小白一個(gè),把學(xué)習(xí)經(jīng)驗(yàn)分享一下,,希望高手指點(diǎn)。。。
首先你要有C#基礎(chǔ)吧,
http://www.runoob.com/csharp/csharp-operators.html;其次你要知道數(shù)據(jù)庫(kù)是干嘛用的,可以百度搜;
安裝VS2017;這個(gè)是C#開(kāi)發(fā)環(huán)境,也可以弄數(shù)據(jù)庫(kù);
然后就新建一個(gè)C#桌面應(yīng)用,畫(huà)一個(gè)按鈕
數(shù)據(jù)庫(kù)怎么弄呢,
https://jingyan.baidu.com/album/9f63fb91893ac3c8410f0e58.html?picindex=1;
窗體應(yīng)用怎么連接數(shù)據(jù)庫(kù)呢
https://www.cnblogs.com/makqiq/p/5882351.html下圖是我設(shè)置的表,以及窗體查詢數(shù)據(jù)庫(kù)里的數(shù)據(jù)
點(diǎn)擊運(yùn)行
下面附上程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp4
{
public partial class Form1 : Form //窗體1
{
private string connectString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\123\Documents\mydata.mdf;Integrated Security=True;Connect Timeout=30";//這個(gè)是連接數(shù)據(jù)庫(kù)的字符串,右擊你建立的數(shù)據(jù)庫(kù),屬性,連接字符串復(fù)制過(guò)來(lái),記得加上@哦
public Form1()
{
InitializeComponent();//初始化
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) //按鈕點(diǎn)擊事件
{
SqlConnection sqlCnt = new SqlConnection(connectString);//實(shí)例化sqlConnection
sqlCnt.Open(); //打開(kāi)數(shù)據(jù)庫(kù)
MessageBox.Show("數(shù)據(jù)庫(kù)已打開(kāi)");//打印數(shù)據(jù)庫(kù)
SqlCommand command = sqlCnt .CreateCommand();//實(shí)例化SqlCommand
command.CommandType = CommandType.Text; //這個(gè)是執(zhí)行SQL語(yǔ)句
command.CommandText = "SELECT*FROM dbo.[Table]"; //查詢你建立的表格
SqlDataReader reader = command.ExecuteReader(); //執(zhí)行SQL,返回一個(gè)“流”
while (reader.Read())
{
MessageBox.Show(Convert.ToString ( reader["id"])+ Convert.ToString(reader["姓名"]) + Convert.ToString(reader["年齡"])); // 打印出每個(gè)用戶的信息
}
sqlCnt.Close();//關(guān)閉數(shù)據(jù)庫(kù)
}
}
}
[ 此帖被工控最強(qiáng)王者在2019-01-22 16:18重新編輯 ]