插入文本框数据到数据库表 [英] Insert data into database table with text box
问题描述
我试图将数据插入到表中,我看到了code snipplet似乎此人,但对我的工作!
我不知道我在做什么错了,因为我不知道数据库处理的asp.net。可有人请什么错与code告诉我?
I'm trying to insert data into a table and the code snipplet I saw seems to work for that person but for me! I don't know what I'm doing wrong because I don't know database handling for asp.net. Can someone please tell me whats wrong with the code?
public partial class CompanyLogin : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = @".\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\VCtemps.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sql = "insert into company values(@CompName, @BusinessType, @Pword)";
OdbcCommand cmd = new OdbcCommand(sql);
string CompName = txtCompName.Text;
string BusinessType = DropDownList1.Text;
string Pword = txtPassword.Text;
cmd.Connection = conn;
cmd.CommandText = "insert into company(CompName, BusinessType, Pword) Values(@CompName,@BusinessType,@Pword);";
cmd.Parameters.AddWithValue("@CompName",SqlDbType.VarChar);
cmd.Parameters.AddWithValue("@BusinessType",SqlDbType.VarChar);
cmd.Parameters.AddWithValue("@Pword",SqlDbType.VarChar);
cmd.ExecuteNonQuery();
conn.Close();
txtCompName.Text = "";
txtPassword.Text = "";
DropDownList1.Text = "";
}
}
在code感谢我固定你们,但是当我运行它,或者,当我点击注册按钮,我收到以下错误
I fixed the code thanks to you guys but when I run it or when I click the register button I get the following error
的ExecuteNonQuery需要一个开放和可用的连接。连接的当前状态为已关闭
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed
推荐答案
您可以调整您的查询 - 删除值
You can adjust your query - by deleting values
cmd.CommandText = "insert into company(CompName, BusinessType, Pword) values('"+ CompName + "','"+ BusinessType + "','" + Pword + "')
诺塔:我建议你也可以使用 SqlCommand.Parameters.AddWithValue方法
和添加此code:
cmd.CommandText = "insert into company(CompName, BusinessType, Pword) Values(@CompName,@BusinessType,@Pword);"
cmd.Parameters.AddWithValue("@CompName",);
cmd.Parameters.AddWithValue("@BusinessType",);
cmd.Parameters.AddWithValue("@Pword",);
cmd.ExecuteNonQuery();
这篇关于插入文本框数据到数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!