将二进制数据从文本框插入列

时间:2013-09-20 05:01:52

标签: c# sql-server tsql ado.net

可以请一些人告诉我如何从SQL数据库中的文本框插入数据,但是以二进制格式。这是我的代码的一部分:

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = @"Data Source=" + File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2db" + ";" + "User ID=" + File.ReadAllText("User.ini") + ";" + "Password=" + File.ReadAllText("Password.ini");
    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "INSERT INTO server (id, name, ip, inner_ip, ageLimit, pk_flag, kind, port, region) VALUES (@id, @name, @ip, @inner_ip, @ageLimit, @pk_flag, @kind, @port, @region)";

        command.Parameters.AddWithValue("@id", textBox1.Text);
        command.Parameters.AddWithValue("@name", textBox2.Text);
        command.Parameters.AddWithValue("@ip", textBox3.Text);
        command.Parameters.AddWithValue("@inner_ip", textBox4.Text);
        command.Parameters.AddWithValue("@ageLimit", textBox5.Text);
        command.Parameters.AddWithValue("@pk_flag", textBox6.Text);
        command.Parameters.AddWithValue("@kind", textBox7.Text);
        command.Parameters.AddWithValue("@port", textBox8.Text);
        command.Parameters.AddWithValue("@region", textBox9.Text);
        connection.Open();
        command.ExecuteNonQuery();
}

2 个答案:

答案 0 :(得分:0)

在该文本框的ONBLUR事件上将该文本更改为二进制格式

借助代码

String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

然后将该二进制数据插入到您的列中

答案 1 :(得分:0)

解决: 我在SQL Query上使用过,更简单: command.CommandText = "INSERT INTO server (id, name, ip, inner_ip, ageLimit, pk_flag, kind, port, region) VALUES (CONVERT(binary,@id), @name, @ip, @inner_ip, @ageLimit, @pk_flag, @kind, @port, @region)";

相关问题