有关连接数据库的问题? [英] questions about connecting to database ?

查看:90
本文介绍了有关连接数据库的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择一个变量中的select语句的结果,如果选择多个变量,如何将结果划分为多个变量.

How can I receive the result of a select statement in a variable and how can I divide the result into more than one variable if I am select more than one variable.

推荐答案

尝试:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT iD, description FROM PurchaseTypes", con))
        {
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", iD, desc);
                }
            }
        }
    }



在OP中:



From the OP:

sql = "select amount from data where password=''" + txtpassword.Text + "''";
cmd = new SqlCommand(sql, con);
if (rdbAdd.Checked == true)
{
    if (txtpassword.Text.Length == 7)
    {
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        try
        {
            reader.Read();
            amount=(int)reader["Amount"];



那是不一样的:您不检查reader.Read()的返回结果-如果没有数据,它将返回false,并且如果尝试使用它,则会出现错误,如您所见. />
此外,请勿将字符串连接起来以形成动态SQL:您可能会遭受意外或蓄意的SQL注入攻击,这很可能会破坏数据库,从而使您大开方便.请改用参数化查询:



That is not the same: you do not check the return result of reader.Read() - if you have no data, it will return false and you will get an error if you try to use it, as you have seen.

In addition, do not concatenate strings to form dynamic SQL: you leave yourself wide open to an accidental or deliberate SQL Injection attack, which could destroy your database. Use parametrized queries instead:

sql = "select amount from data where password=@PW";
cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@PW", txtpassword.Text);



哦,不要将密码清楚地存储在数据库中:重大的安全风险! :laugh:



Oh, and don''t store passwords in clear in your database: major security risk! :laugh:


请仔细阅读这篇文章

数据库编程
Please go through with this Article

Database Programing


您可以将数据返回到使用DataAdapter,然后遍历使用Cells属性返回的每个DataRow. 示例 [示例 [ ^ ].
You can return the data into a DataTable by using a DataAdapter and then iterate over each DataRow returned using the Cells property. Example[^].

You can also use a DataReader and read the returned rows one by one and index into the row for the column required. Example[^].


这篇关于有关连接数据库的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆