调用从数据库到文本字段中的值 - 自定义错误自定义、字段、文本、错误

2023-09-06 10:49:30 作者:在雾里告白

我有以下的code在我的Page_Load函数,它基本上是从基础上压缩code用户输入一个数据库返回一个值。问题是,我遇到了一个自定义错误的问题。当我的另外两个文本框获得自动填充,如果我等待5分钟,然后提交,我会得到一个错误,但是,如果我提出5分钟之内,一切都按预期工作。请你让我知道,如果我从数据库中调用值的方式是错误的,或者我怎么可能会修复这个错误?这是错误:

 <! -  Web.config配置文件 - >

<结构>
    <的System.Web>
        <的customErrors模式=关/>
    < /system.web>
< /结构>
 

这是我的code,(这是pretty的基础,我是新来编程):

 保护无效的Page_Load(对象发件人,EventArgs的)
{

    如果(txtzip.Text.Length == 5)
    {
        SqlCommand的COMM1 =新的SqlCommand(SELECT TOP(1)* FROM zip_ code,其中的zip ='+ Convert.ToInt32(txtzip.Text)+',康涅狄格州);

        conn.Open();
        SqlDataReader的DR1 = Comm1.ExecuteReader();
        如果(DR1.Read())
        {
            txtstate.Text = DR1.GetValue(2)的ToString();
            txtcity.Text = DR1.GetValue(1)的ToString();
        }

        conn.Close();
    }
 

这是我的配置文件(请注意,我代替我的凭据......):

 < XML版本=1.0&GT?;
<结构>
  <的ConnectionStrings>

    <添加名称=aConn的connectionString =数据源= .......;初始目录= aspData;集成安全性=真
      的providerName =System.Data.SqlClient的/>
  < /的ConnectionStrings>
  <的System.Web>
    <编译调试=真正的targetFramework =4.5>
      <组件>
        <添加组件=System.Design,版本= 4.0.0.0,文化=中性公钥= .../>
        <添加组件=System.Web.Extensions.Design,版本= 4.0.0.0,文化=中性公钥= ....../>
        <添加组件=System.Windows.Forms的,版本= 4.0.0.0,文化=中性公钥= ......../>
      < /组件>
    < /编译>
    <的httpRuntime targetFramework =4.5/>
  < /system.web>
< /结构>
 
数据库字段值存储修改使用

解决方案

好了,一些事情是错误的,从你说的话,好像连接被关闭:

当你做了你应该创建连接,当你需要它,它释放 的zip code是int类型的不是。 Convert.ToInt32 会给你带来意想不到的结果,因为领先 零点将被删除。 您还需要学习如何使用参数化查询,就会避免 SQL注入,也节省您的语法错误。 SELECT * + .GetValue()是receipe了一些错误,如果你曾经 修改表结构或查询,你可以把你的code,而不是列索引使用的名称,并且不使用通配符 * 选择特定的领域。 最后但并非最不重要的,使用的语句使用更 处理你的对象的有效方式。

 使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
    connection.Open();

    使用(SqlCommand的命令=新的SqlCommand(
    选择TOP(1)市,州FROM zip_ code,其中的zip = @zip,连接))
    {

        command.Parameters.Add(新的SqlParameter(拉链,txtzip.Text));

        SqlDataReader的读卡器= Command.ExecuteReader却();
        如果(reader.HasRows())
        {
            VAR城市=读卡器[城市]的ToString()。
            VAR状态=读卡器[状态]的ToString()。

            Console.WriteLine(城市= {0},状态= {1},
                市,
                州)

            txtstate.Text =城市
            txtcity.Text =状态;
        }
    }
}
 

I have the following code in my page_load function which basically returns a value from a database based on the zip code the user enters. The problem is, I am running into a custom error issue. When my other two text fields get auto filled, if I wait 5 mins then submit, I will get an error, however, if I submit within 5 mins, everything works as expected. could you please let me know if the way I calling values from the database is wrong, or how I might fix this error? this is the error:

<!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

This is my code, (it is pretty basic, I am new to programming):

protected void Page_Load(object sender, EventArgs e)
{

    if (txtzip.Text.Length == 5)
    {
        SqlCommand Comm1 = new SqlCommand("SELECT TOP(1) * FROM zip_code WHERE zip = '" + Convert.ToInt32(txtzip.Text) + "'", conn);

        conn.Open();
        SqlDataReader DR1 = Comm1.ExecuteReader();
        if (DR1.Read())
        {
            txtstate.Text = DR1.GetValue(2).ToString();
            txtcity.Text = DR1.GetValue(1).ToString();
        }

        conn.Close();
    }

This is my config file (please note that I replaced my credentials with ......):

<?xml version="1.0"?>
<configuration>
  <connectionStrings>

    <add name="aConn" connectionString="Data Source=.......;Initial Catalog=aspData;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=......"/>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=......."/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=........"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>

解决方案

Ok, few things are wrong, from what you are saying , it seems the connection gets closed:

You should create connection when you need it, release it when you done A zip code is not of type int. Convert.ToInt32 will give you unexpected result because the leading zero will be removed. You also need to learn how to use parameterized queries, it will avoid SQL injection and also save you from syntax errors. SELECT * + .GetValue() is the receipe for some bugs, if you ever modify the table structure or the query you can break your code, instead of column index use the name, and don't use the wildcard * select the specific field. And last but not least, make use of using statement it is more efficient way of disposing your objects.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(
    "SELECT TOP(1) city, state  FROM zip_code WHERE zip = @zip", connection))
    {

        command.Parameters.Add(new SqlParameter("zip", txtzip.Text));

        SqlDataReader reader = command.ExecuteReader();
        if(reader.HasRows())
        {
            var city = reader["city"].ToString();
            var state = reader["state"].ToString();

            Console.WriteLine("City = {0}, State = {1}",
                city,
                state)      

            txtstate.Text = city
            txtcity.Text = state;
        }
    }
}