日期:2014-05-18  浏览次数:21117 次

求助,OLEDB向ACCESS数据库添加数据的问题
有5个textbox,ID分别为name,year,address,phone,email,对应数据库中字段为zname,zyear,zaddress,zphone,zemail。有一个button控件ID为submit。想实现点击按钮将文本框中数据写入数据库中。如何实现?
C# code
    protected void submit_Click(object sender, EventArgs e)
    {
        //数据库连接
         OleDbConnection con=new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\ceshi\App_Data\frs2012.mdb; ");
        //插入数据命令
         OleDbCommand cmd = new OleDbCommand("insert into connect(name,year,address,phone,email) values(zname,zyear,zaddress,zphone,zemail) ", con);
         cmd.Parameters.AddWithValue("@zname ", this.name.Text.Trim());
         cmd.Parameters.AddWithValue("@zyear ", this.year.Text.Trim());
         cmd.Parameters.AddWithValue("@zaddress ", this.address.Text.Trim());
         cmd.Parameters.AddWithValue("@zphone ", this.phone.Text.Trim());
         cmd.Parameters.AddWithValue("@zemail ", this.email.Text.Trim());
        //打开数据库连接
        con.Open();
          //执行
          cmd.ExecuteNonQuery();
        //关闭连接
         con.Close();
    }
}



------解决方案--------------------
参数化
//插入数据命令
OleDbCommand cmd = new OleDbCommand("insert into connect(name,year,address,phone,email) values(@zname,@zyear,@zaddress,@zphone,@zemail)", con);
cmd.Parameters.AddWithValue("@zname", this.name.Text.Trim());//不要有空格,后面也一样
cmd.Parameters.AddWithValue("@zyear", this.year.Text.Trim());
cmd.Parameters.AddWithValue("@zaddress", this.address.Text.Trim());
cmd.Parameters.AddWithValue("@zphone", this.phone.Text.Trim());
cmd.Parameters.AddWithValue("@zemail", this.email.Text.Trim());
------解决方案--------------------
有5个textbox,ID分别为name,year,address,phone,email,对应数据库中字段为zname,zyear,zaddress,zphone,zemail
你都写的这么清楚,还能搞错了。
 
protected void submit_Click(object sender, EventArgs e)
{
//数据库连接
OleDbConnection con=new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\ceshi\App_Data\frs2012.mdb; ");
//插入数据命令
OleDbCommand cmd = new OleDbCommand("insert into connect(zname,zyear,zaddress,zphone,zemail) values(@name,@year,@address,@phone,@email) ", con);
cmd.Parameters.AddWithValue("@name ", this.name.Text.Trim());
cmd.Parameters.AddWithValue("@year ", this.year.Text.Trim());
cmd.Parameters.AddWithValue("@address ", this.address.Text.Trim());
cmd.Parameters.AddWithValue("@phone ", this.phone.Text.Trim());
cmd.Parameters.AddWithValue("@email ", this.email.Text.Trim());
//打开数据库连接
con.Open();
//执行
cmd.ExecuteNonQuery();
//关闭连接
con.Close();
}
}
------解决方案--------------------
insert into connect......
改成
insert into [connect]......

connect可能是access的关键字。