一个连接access的问题,请帮助看看代码。
我用的是VS2005C#环境,问题出在哪里,请帮助看看。插入数据时错。using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace access
{
class DB
{
OleDbConnection Conn = null;
public DB()
{
//string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= Application.StartupPath"(@"mydb.mdb");
//上边的Application.StartupPath在我这里不出来,不知道为什么。
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; " + @"Data Source=e:\mydb.mdb";
Conn = new OleDbConnection(strConn);
}
public DataTable query(string sql)
{
OleDbCommand com = new OleDbCommand (sql, Conn);
OleDbDataAdapter ad = new OleDbDataAdapter(com);
DataTable dt = new DataTable ();
ad.Fill(dt);
return dt;
}
public int update(string sql)
{
OleDbCommand com = new OleDbCommand(sql, Conn);
Conn.Open();
int i = com.ExecuteNonQuery();
Conn.Close();
return i;
}
}
}
----------------------------------------------------------------
窗体中实现插入数据,有问题。
-----------------------------------------------------------------
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace access
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DB db = new DB () ;
string sql = "select stu_id,stu_name, password from student";
DataTable dt = db.query(sql);
ListViewItem item = null;
foreach(DataRow dr in dt.Rows)
{
item = new ListViewItem();
item.Text = Convert.ToString(dr["stu_id"]);
item.SubItems.Add(Convert.ToString(dr["stu_name"]));
item.SubItems.Add(Convert.ToString(dr["password"]));
listView1.Items.Add(item);
}
}
private void button2_Click(object sender, EventArgs e)
{
DB db = new DB();
string sql = string.Format("insert into student(stu_name, password) values('{0}', '{1}')", textBox1.Text, textBox2.Text);
db.update(sql);
}
}
}
access.rar
(27.46 KB)
[ 本帖最后由 zhangyi_hrb 于 2010-3-29 10:01 编辑 ]