0

我正在从文件中读取并将值插入到我的表中。但是我没有插入所有列。我得到一个我无法放置的溢出异常。文件内容如下:

Huseyin Sabirli 13/11/1978 Nicosia MBRh+ 05333768275 Kelebek Street, No:11, Taskinkoy, Nicosia, KKTC

创建表的代码

c.CommandText = "CREATE TABLE patients (patientid AUTOINCREMENT PRIMARY KEY, firstlastname CHAR, birthdate CHAR, birthplace CHAR, gender CHAR, bloodtype CHAR, telnum long, address CHAR)";

插入代码是:

 c.CommandText = "INSERT INTO patients (" +
                            "firstlastname, birthdate, birthplace, bloodtype, telnum, address" +
                                ") VALUES ('" +
                                info.Substring(0, 15) + "', '" +
                                info.Substring(24, 10) + "', '" +
                                info.Substring(35, 9) + "', '" +
                                info.Substring(47, 5) + "', '" +
                                info.Substring(53, 11) + "', '" +
                                info.Substring(64) + "')";


            c.ExecuteNonQuery();

在行抛出溢出异常c.ExecuteNonQuery();

注意:实际文件中的间距与上面显示的不同。这解释了 substring 函数中的变体长度。谢谢

4

1 回答 1

0

我认为您的子字符串表达式有问题。这不太对。
@Remou 的评论还确定了异常的当前原因。
当然,字符串连接存在很大问题。
将值传递给数据库引擎时,这不是正确的做法。
(引用问题,Sql Injection Attacks)

正确的方法应该是:(
创建表后将 telnum 字段更改为 char 数据类型,因为它不是实数值)

CREATE TABLE patients 
     (patientid AUTOINCREMENT PRIMARY KEY, 
     firstlastname CHAR(15), 
     birthdate CHAR(10), 
     birthplace CHAR(8), 
     gender CHAR(1), 
     bloodtype CHAR(4), 
     telnum CHAR(12), 
     address CHAR(255))
......

string info = "Huseyin Sabirli 13/11/1978 Nicosia MBRh+ 05333768275 " + 
              "Kelebek Street, No:11, Taskinkoy, Nicosia, KKTC";

string name = info.Substring(0, 15);
string date = info.Substring(16, 11)
string place = info.Substring(27, 8);
string blood = info.Substring(37, 4);
string num = info.Substring(41, 12);
string address = info.Substring(53);

string cmdText = "INSERT INTO patients (" +
                 "firstlastname, birthdate, birthplace, bloodtype, telnum, address) " +
                 "VALUES (?,?,?,?,?,?)"
using(OleDbConnection cn = getConnection())
{
    cn.Open();
    using(OleDbCommand cmd = new OleDbCommand(cmdText, cn))
    {
        cmd.Parameters.AddWithValue("name", name);
        cmd.Parameters.AddWithValue("date", date);
        cmd.Parameters.AddWithValue("place", place);
        cmd.Parameters.AddWithValue("blood", blood);
        cmd.Parameters.AddWithValue("num", num);
        cmd.Parameters.AddWithValue("address", address);
        cmd.ExecuteNonQuery();
    }
}
于 2012-12-22T11:19:19.850 回答