带插入数据的Nimiety文本

时间:2015-08-22 13:28:14

标签: c# sql-server wpf

我正在尝试在数据库中插入数据(WPF)。这是我的连接代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.Sql;
namespace sba1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SqlConnection sc = new SqlConnection("Data Source=ASUS\\SQL;Initial Catalog=test;Integrated Security=True");
        SqlCommand cmd;
        public MainWindow()
        {
            InitializeComponent();
        }


        private void btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                sc.Open();

                cmd = new SqlCommand("insert into prsn(id,name) values ('" + txtid + "' , '" + txtname + "')", sc);
                cmd.ExecuteNonQuery();
                MessageBox.Show("update sucsessful to database");
                sc.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}

prsn表有两列(id[unique] - name)。例如,当我想用​​name = Doe插入id = 914524时,表格中的结果为:

id = system.windows.control.textbox: 914524
name = system.windows.control.textbox: Doe

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:1)

您应使用Text的{​​{1}}属性,如:

TextBox

顺便说一下,您应该始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。