2020年2月29日 星期六

手把手建立第一個SQL程式

成果大概是這樣



首先建立一個widnows form的範例方便顯示
在專案中右鍵建立一個新增項目

選擇左邊的資料庫
到伺服器總管新增一個資料表

點兩下database1.mdf會產生這個xsd檔,把新建立的table丟過去(這裡建議新建的table要改自己的名字,不然讀取會出錯,我就是錯了之後又改成table123才能正常更新)


新增自己要的欄位,並且要給一個主鍵值(鑰匙那個)

再來就把畫面做出來跟你要新增的資料欄位配合,並新增dataset跟datagrid


datagrid選擇資料來源要找到最細的table才會跟表格有連結喔~

最後會長這樣
新增資料欄位的內部寫法請看下方


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 WindowsFormsAppSQLtest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Add_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::WindowsFormsAppSQLtest.Properties.Settings.Default.Database1ConnectionString);
//SqlConnection cn = new SqlConnection(global::);
try
{
string sql = "INSERT INTO Table123 (Id,name,money) values(" + txtBox_ID.Text + ",'" + txtBox_Name.Text + "'," + txtBox_Money.Text + ");";
SqlCommand exeSQL = new SqlCommand(sql, cn);
cn.Open();
exeSQL.BeginExecuteNonQuery();
MessageBox.Show("add a new record", "Msg", MessageBoxButtons.OK, MessageBoxIcon.Information);
//this.tableTableAdapter.Fill(this.database1DataSet1.Table);
this.table123TableAdapter.Fill(this.database1DataSet1.Table123);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
private void database1DataSet1BindingSource_CurrentChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: 這行程式碼會將資料載入 'database1DataSet1.Table' 資料表。您可以視需要進行移動或移除。
this.table123TableAdapter.Fill(this.database1DataSet1.Table123);
}
}
}