如何从文本框中将数据插入到数据库中

huangapple go评论58阅读模式
英文:

How to insert data into DB from textbox

问题

错误:

> Msg 2809,级别 16,状态 1,第 13 行
> 请求过程 'member_master_tbl' 失败,因为 'member_master_tbl' 是一个表对象。

问题是什么?

英文:

Consider:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Elibrary_management2
{
    public partial class user_registration : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        // Signup button click
        protected void Button1_Click(object sender, EventArgs e)
        {
            // Response.Write("<script>alert('successfull')</script>");
            try
            {
                SqlConnection con = new SqlConnection(strcon);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                string sqlquary = ("insert into member_master_tbl(full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password,account_status) values(@full_name,dob,@contact_no,@email,@state,@city,@pincode,@full_address,@member_id,@password,@account_status");
                SqlCommand cmd = new SqlCommand(sqlquary, con);
                cmd.Parameters.AddWithValue("@full_name", TextBox1.Text.Trim());
                cmd.Parameters.AddWithValue("@dob", TextBox2.Text.Trim());
                cmd.Parameters.AddWithValue("@contact_no", TextBox2.Text.Trim());
                cmd.Parameters.AddWithValue("@email", TextBox4.Text.Trim());
                cmd.Parameters.AddWithValue("@state", DropDownList1.SelectedItem.Value);
                cmd.Parameters.AddWithValue("@city", TextBox6.Text.Trim());
                cmd.Parameters.AddWithValue("@pincode", TextBox7.Text.Trim());
                cmd.Parameters.AddWithValue("@full_address", TextBox8.Text.Trim());
                cmd.Parameters.AddWithValue("@member_id", TextBox9.Text.Trim());
                cmd.Parameters.AddWithValue("@password", TextBox5.Text.Trim());
                cmd.Parameters.AddWithValue("@account_status", "pending");

                cmd.ExecuteNonQuery();
                con.Close();
                Response.Write("<script>alert('Signup Successfull');</script>");
            }
            catch(Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }
        }
    }
}

Error:

> Msg 2809, Level 16, State 1, Line 13
> The request for procedure 'member_master_tbl' failed because 'member_master_tbl' is a table object.

What is the problem?

答案1

得分: 1

你的错误有 多个 原因。

首先,你有

member_master_tbl(

好吧,你的表名里有个 "(" - 这会让 SQL 感到困惑。

(你真的有一个叫上面那个名字的表吗?)

所以,在表名后面加一个空格

接下来:永远不要让代码像那样超出屏幕。你无法看到也无法查看 SQL。这就像在黑暗房间里盲目编码一样。你看不到你的代码,因此你只是在猜测和尝试让它工作。

用括号括起字符串的事实表明你只是在猜测。

连接将始终被关闭。由于它总是被你之前的正确工作代码关闭的,那么你就永远不需要测试或检查你的连接对象,对吗?换句话说,假设你之前的代码是好的和正确的,那么你就永远不需要关闭连接!

而且,由于假设你之前的代码是正确的,那么你也永远不需要检查连接是否打开!

如何确保你永远不会有那个杂乱的连接?

答案是:你让 系统 来处理这个,它会为你关闭、清理和处理连接,这就是如何做到的!

那么,你如何做到这一点呢?你采用 using 块。它实际上会 节省 你的代码!

更糟糕的是,由于你的 SQL 语句超出了屏幕的边缘:请注意你缺少了 VALUES 列表的关闭 ")"。

但再次说一遍,你看不到或注意不到这一点,对吧!

记住,好的开发者其实并不那么出色。

但是,他们真正擅长的是什么?他们编写易于阅读的代码,因此查找错误也变得 容易!

换句话说,好的开发者实际上更擅长编写易于阅读和修复的代码,而不是拥有超级大脑来发现错误!

接下来:

强制 类型化你的参数。这意味着如果一个值是 "int",那么告诉系统该值应该是 int,依此类推。

所以,让我们修复表名,因为你的表名不是 "member_master_tbl("

没有空格,你会看到一个错误消息,说这看起来像一个函数!

例如:abc(

将你的 SQL 连接块包装在 using 语句中。这意味着你可以提早下班,参加欢乐时光,有时间幸运地找到机会。这还意味着连接会被自动关闭,被自动释放,你不需要在意或担心它(再次,这让事情变得容易)。

你会发现,好的程序员不是更擅长编码,而是学会了避免难以阅读和修复的代码。结果是这种代码就像小孩子的游戏,因为它更容易编写、阅读和修复。

所以,我建议从以下代码开始:

using (SqlConnection con = new SqlConnection(strcon))
{
    string sqlquary =
        @"insert into member_master_tbl
        (
            full_name, dob, contact_no, email, state, city, pincode,
            full_address, member_id, password, account_status
        )
        VALUES
        (
            @full_name, dob, @contact_no, @email, @state, @city, @pincode,
            @full_address, @member_id, @password, @account_status
        )";

    using (SqlCommand cmd = new SqlCommand(sqlquary, con))
    {
        cmd.Parameters.Add("@full_name", SqlDbType.NVarChar).Value = TextBox1.Text;
        cmd.Parameters.Add("@dob", SqlDbType.Date).Value = TextBox2.Text;
        cmd.Parameters.Add("@contact_no", SqlDbType.NVarChar).Value = TextBox2.Text;
        cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = TextBox4.Text;
        cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = DropDownList1.SelectedItem.Value;
        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = TextBox6.Text;
        cmd.Parameters.Add("@pincode", SqlDbType.Int).Value = TextBox7.Text;
        cmd.Parameters.Add("@full_address", SqlDbType.NVarChar).Value = TextBox8.Text;
        cmd.Parameters.Add("@member_id", SqlDbType.Int).Value = TextBox9.Text;
        cmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = TextBox5.Text;
        cmd.Parameters.Add("@account_status", SqlDbType.NVarChar).Value = "pending";

        con.Open();
        cmd.ExecuteNonQuery();
    }
}
Response.Write("<script>alert('Signup Successfull');</script>");

即使上面的代码有一些错误,它也会更容易更改、修复和阅读。然而,如上所示强制类型化参数,并编辑和修复上面的内容以匹配表中的数据类型。

至于文本框的名称?真的,除非网页上只有 1 或 2 个文本框,否则不要使用 TextBox1。超过 1 或 2 个文本框的页面上:那么请为每个文本框分配一个易于阅读的 ID,表示它的含义。

那么,我会如何编写上面的代码?

我的版本看起来像这样:

int PK = General.FwriterAdd(EditArea, "member_master_tbl")

上面的 EditArea 是一个 div。因为手工编写一个页面上的控件的发送或加载在编码一天后?那太多工作了!

所以,我编写了 *

英文:

Your errors are for several reasons.

Firstly, you have

member_master_tbl(

Well, you have a table name with "(" in it - it going to confuse SQL.

(Do you really have a table named above?)

So, place a space after the table name

Next up: don't ever let code spread off the screen like that. You can't see, nor look at the SQL. It becomes like coding in a dark room with a blindfold on. You can't see your code, and as result, you're just now guessing and hacking to make this work.

The fact of surrounding the string with "(" shows that you just guessing now.

The connection will always have been closed. Since it always been closed by your correct previous working code, then you never will have to test or check your connection object, right? In other words, work on the assumption that your previous code was good, and correct, and since one makes that assumption, then you never have to close the connection!

And since your previous code is assumed to be correct, then you never have to check if the connection is open either!

And how do you always make sure you don't have that stray connection?

Answer: you let the system take care of this, and it will always have closed and cleaned up and disposed the connection for you, that's how!

And how do you do the above? You adopt using blocks. It will actually save you writing code!

Worse yet, since your SQL statement runs off the edge of the screen: note how your missing the closing ")" for your VALUES list.

but then again, you can't see or notice this, right!

Remember, good developers are not really that good.

But, what they do really fantastically? They write code that humans can read easy, so then seeing errors is also easy!

In other words, good developers are actually better at writing code that easy to see and fix, not that they have super brains that see errors!

Next up:

Strong type your parameters. That means if a value is "int", then tell the system that the value supposed to be int, etc.

So, let's fix the table name, since your table name is not "member_master_tbl("

Without a space, you seeing a error message that this looks like a function!

eg:    abc(

Wrap your SQL connection block in using statements. This means you can leave work early, make happy hour and have time to get lucky. It also means the connection will be closed for you, disposed for you, and you don't care, or nor have to worry about it (again, makes things easy).

You find that good coders are not better at coding, but they learned to avoid code that hard to read, and hard to fix. The result is such code is child's play, since it was easer to write, read, fix.

So, I would suggest this code as a start:

using (SqlConnection con = new SqlConnection(strcon))
{
    string sqlquary =
        @"insert into member_master_tbl
        (
            full_name, dob, contact_no, email, state, city, pincode,
            full_address, member_id, password, account_status
        )
        VALUES
        (
            @full_name, dob, @contact_no, @email, @state, @city, @pincode,
            @full_address, @member_id, @password, @account_status
        )";

    using (SqlCommand cmd = new SqlCommand(sqlquary, con))
    {
        cmd.Parameters.Add("@full_name", SqlDbType.NVarChar).Value = TextBox1.Text;
        cmd.Parameters.Add("@dob", SqlDbType.Date).Value = TextBox2.Text;
        cmd.Parameters.Add("@contact_no", SqlDbType.NVarChar).Value = TextBox2.Text;
        cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = TextBox4.Text;
        cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = DropDownList1.SelectedItem.Value;
        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = TextBox6.Text;
        cmd.Parameters.Add("@pincode", SqlDbType.Int).Value = TextBox7.Text;
        cmd.Parameters.Add("@full_address", SqlDbType.NVarChar).Value = TextBox8.Text;
        cmd.Parameters.Add("@member_id", SqlDbType.Int).Value = TextBox9.Text;
        cmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = TextBox5.Text;
        cmd.Parameters.Add("@account_status", SqlDbType.NVarChar).Value = "pending";

        con.Open();
        cmd.ExecuteNonQuery();
    }
}
Response.Write("<script>alert('Signup Successfull');</script>");

Even if the above code has some errors, it going to be far more easy to change, fix, and read. However, strong type the parameter's as above shows, and edit + fix the above to MATCH the data types in the table.

And those name for text boxes? Really, don't use TextBox1 unless there is only 1 or 2 text boxes on the webform. Beyond 1 or 2 text boxes on the page: then always give each text box a nice readable id of what it means.

So, how would I have written the above code?

My version looks like this:

       int PK = General.FwriterAdd(EditArea, "member_master_tbl")

EditArea in above is a div. Since after one day of hand coding the sending or loading of controls on a page? It is way too much work!

So, I wrote one general routine that takes the controls, and sends them to the database for me, and now for every page with a bunch of controls, I don't have to write the same thing over and over, and I have one routine that works for all web pages. But, let's leave how that code works for another day and time.

huangapple
  • 本文由 发表于 2023年6月5日 16:38:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定