折騰了好久,蒙圈了很久,終于調(diào)用數(shù)據(jù)庫成功,小白一個,把學(xué)習(xí)經(jīng)驗分享一下,,希望高手指點(diǎn)。。。
首先你要有C#基礎(chǔ)吧,
http://www.runoob.com/csharp/csharp-operators.html;其次你要知道數(shù)據(jù)庫是干嘛用的,可以百度搜;
安裝VS2017;這個是C#開發(fā)環(huán)境,也可以弄數(shù)據(jù)庫;
然后就新建一個C#桌面應(yīng)用,畫一個按鈕
數(shù)據(jù)庫怎么弄呢,
https://jingyan.baidu.com/album/9f63fb91893ac3c8410f0e58.html?picindex=1;
窗體應(yīng)用怎么連接數(shù)據(jù)庫呢
https://www.cnblogs.com/makqiq/p/5882351.html下圖是我設(shè)置的表,以及窗體查詢數(shù)據(jù)庫里的數(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";//這個是連接數(shù)據(jù)庫的字符串,右擊你建立的數(shù)據(jù)庫,屬性,連接字符串復(fù)制過來,記得加上@哦
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);//實例化sqlConnection
sqlCnt.Open(); //打開數(shù)據(jù)庫
MessageBox.Show("數(shù)據(jù)庫已打開");//打印數(shù)據(jù)庫
SqlCommand command = sqlCnt .CreateCommand();//實例化SqlCommand
command.CommandType = CommandType.Text; //這個是執(zhí)行SQL語句
command.CommandText = "SELECT*FROM dbo.[Table]"; //查詢你建立的表格
SqlDataReader reader = command.ExecuteReader(); //執(zhí)行SQL,返回一個“流”
while (reader.Read())
{
MessageBox.Show(Convert.ToString ( reader["id"])+ Convert.ToString(reader["姓名"]) + Convert.ToString(reader["年齡"])); // 打印出每個用戶的信息
}
sqlCnt.Close();//關(guān)閉數(shù)據(jù)庫
}
}
}
[ 此帖被工控最強(qiáng)王者在2019-01-22 16:18重新編輯 ]