主要功能:
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
运行结果:
点击“显示用户信息”
点击“下一条”
点击“上一条”