如何在文本框中验证邮政编码并将相应的州/城市输出与其各自的标签相对应

问题描述 投票:0回答:1

我正在尝试编写一个非常直接的程序,从我的SQL Server数据库中提取数据。并在文本框中输入的有效邮政编码中输出正确的州和城市。

这是我正在搞乱的一些代码。它显然不起作用我只是尝试。

我能够用一个zip / city相关的所有州填充一个组合框,但就是这样。

// Connection string.
String cnStr;
SqlConnection cn = new SqlConnection();

cnStr = "Data Source=000.00.000.00;Initial Catalog= ;User ID= ;Password= ";

// Assign Connection string to the connection object
cn.ConnectionString = cnStr;

// Open the connection to the SQL Server
cn.Open();

// This statement creates the command object and passes in the SQL statement
// then associates the command to the cn connection object
SqlCommand cmd = new SqlCommand("select distinct state, city from tblZipcodes order by state", cn);

// Open a DataReader
SqlDataReader rdrZip = cmd.ExecuteReader();

cn.Close();

验证在文本框中输入的邮政编码,并将结果状态和城市从SQL Server输出到各自的标签。

c# sql sql-server winforms
1个回答
2
投票

总是使用参数,永远不要构建没有参数的SQL查询,因为它会让你的应用程序对sql injection大开。 你应该使用像这样的where子句

var sql = "select distinct state, city from tblZipcodes where zipcode = @ZipCode";

using (SqlCommand cmd = new SqlCommand(sql))
{
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.Add(new SqlParameter("@ZipCode", SqlDbType.VarChar) { Value = myZipCode.Text });

    SqlDataReader rdrZip = cmd.ExecuteReader();
}

如果您的列类型是qazxsw poi而不是SqlDbType.NVarChar,请使用qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.