主要功能:
1)串連SqlServer 2000資料庫
2)顯示指定資料表中的資料
3)分條顯示查詢結果
組件設計:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public partial class Form1 : Form
{
private BindingManagerBase navigater; //使用BindingManagerBase來移動資料記錄
private DataSet ds;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateHandler dbHandler = new DateHandler();
dbHandler.connectDB();
string commandText = "select * from users ;";
ds = dbHandler.execSqlSelect(commandText, "users");
navigater = this.BindingContext[ds, "users"];
username.DataBindings.Add("Text",ds,"users.username"); //添加資料來源的綁定
password.DataBindings.Add("Text",ds,"users.password");
}
private void button3_Click(object sender, EventArgs e)
{
if (navigater.Position == 0)
{
navigater.Position = navigater.Count - 1;
}
else
{
navigater.Position -= 1;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (navigater.Position == navigater.Count - 1)
{
navigater.Position = 0;
}
else
{
navigater.Position += 1;
}
}
}
DateHandler.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;//SqlConnection和SqlDataAdapter
class DateHandler
{
private SqlConnection con = null; //SQL Server資料庫連接
public string conString = null;
//connect to the MSSQLSERVER Instance
public void connectDB()
{
conString = "Server=localhost;initial catalog=simpledb; User ID=sa; Password=10270213;Connect Timeout=4;";
//catalog 是 data source 的別名,指本次串連的資料庫名, Server指你的資料庫物件,本機資料用localhost
if (con != null)
return;
try
{
con = new SqlConnection(conString);
con.Open();
}
catch (Exception)
{
if (con != null)
con.Dispose();
con = null;
throw;
}
}
public SqlDataReader execSqlSelect1(String commandTest)
{
SqlCommand com = new SqlCommand(commandTest, con);
com.CommandType = CommandType.Text;
com.CommandText = commandTest;
SqlDataReader dateReader = com.ExecuteReader();
return dateReader;
}
//查詢資料,並得到一個DataSet對象。其中newTableName是結果表的表名
public DataSet execSqlSelect(string commandText, string newTableName)
{
SqlDataAdapter dAdapter;
DataSet dSet = new DataSet();
dAdapter = new SqlDataAdapter(commandText, con);
dAdapter.Fill(dSet, newTableName);
return dSet;
}
public int execSqlInsert(String commandTest)
{
SqlCommand com = new SqlCommand(commandTest, con);
com.CommandType = CommandType.Text;
com.CommandText = commandTest;
int row = com.ExecuteNonQuery();
return row;
}
}
資料庫表: users
運行結果:
點擊“顯示使用者資訊”
點擊“下一條”
點擊“上一條”