无法理解我错在哪里,数据库没有存储记录。请帮忙 [英] Can't understand where I am wrong, Database not storing record. Please help

查看:54
本文介绍了无法理解我错在哪里,数据库没有存储记录。请帮忙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button_Pass_Click(object sender, EventArgs e)
        {
            SqlConnection con1 = new SqlConnection("Data Source=JAYI-PC\\SQLEXPRESS;Initial Catalog=db-ub;Integrated Security=True");
            con1.Open();
            Image img = pictureBox_UB.Image;
            byte[] arr;
            ImageConverter converter = new ImageConverter();
            arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
            //SqlCommand cmd1 = new SqlCommand("Insert into Visitors (Image) values('"+arr+"')");
            //cmd1.ExecuteNonQuery();

            string s = "";
            if (comboBox_TOWHOM.SelectedIndex >= 0)
            s = comboBox_TOWHOM.Items[comboBox_TOWHOM.SelectedIndex].ToString();

            string c = "";
            if (comboBox_color.SelectedIndex >= 0)
            c = comboBox_color.Items[comboBox_color.SelectedIndex].ToString();

            string n = "";
            if(numericUpDown_Person.Value >= 0)
            n = numericUpDown_Person.Value.ToString();

            string prps = string.Empty;
            if(radioButton_OFFICIAL.Checked)
            {
                prps = "Official";
            }
            else if(radioButton_PERSONAL.Checked)
            {
                prps = "Personal";
            }

            SqlCommand cmd1 = new SqlCommand("Insert into Visitors(Id,Visitor Name,Organisation Name,Phone No,No of Person,Whom to Visit,Purpose,Color Code,Day In,Time In, Image)values("+textBox_Id.Text+",'" + textBox_NameV.Text + "','" + textBox_Org.Text + "'," + textBox_Phn.Text + ",'" + n + "','" + s + "','" + prps + "','" + c + "','" + textBox_Dayin.Text + "','" + textBox_timeR.Text + "'," + arr + ")",con1);
            cmd1.ExecuteNonQuery();
            MessageBox.Show("Record has been inserted");
            con1.Close();

推荐答案

对于初学者,不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。这也意味着您不需要将数值转换为字符串,以便让SQL再次将它们转换回来...



其次,您的图像赢了即使你确实正常工作也要妥善存储:为什么我得到参数无效。我从数据库中读取图像时出现异常? [ ^ ]解释你在图像上做错了什么,以及如何修复它。



整理出这两个,你的问题可能就会消失。
For starters, do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead. This also means you don't need to convert numeric values to strings, in order to get SQL to convert them right back again...

Secondly, your image won't store properly even if you did get that working: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^] explains what you are doing wrong with the image, and how to fix it.

Sort out those two, and your problem will likely go away.


这篇关于无法理解我错在哪里,数据库没有存储记录。请帮忙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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