C# 用insert into向SQL Server添加一行数据时语法出错,求助!
在textbox输入纯数字时通过,但是只要出现字符或汉字,编译会出错,为什么呢?代码如下,本人菜鸟,请详解一下症结所在,谢谢指教!namespacetest2{publi...
在textbox输入纯数字时通过,但是只要出现字符或汉字,编译会出错,为什么呢?
代码如下,本人菜鸟,请详解一下症结所在,谢谢指教!
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn = new SqlConnection("Data Source=SQLofVE;Initial Catalog=HIV;Integrated Security=True");
private void GetDataGridView()
{
string sql = "select * from tb_User";
dataGridView1.Columns.Clear();
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataTable table = new DataTable();
sda.Fill(table);
dataGridView1.DataSource = table;
}
private void Form1_Load(object sender, EventArgs e)
{
GetDataGridView();
}
private void btn_add_Click(object sender, EventArgs e)
{
string sql = string.Format("insert into tb_User (UserID,UserName,PassWord) VALUES ({0}, {1},{2})", Convert.ToInt16(tb_ID.Text), tb_Name.Text, tb_Psw.Text); //数字可以通过,为何加字母就出错?
SqlCommand scmd = new SqlCommand(sql, conn);
conn.Open();
try
{
int num = scmd.ExecuteNonQuery();
if (num > 0)
{
GetDataGridView();
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
conn.Close();
}
}
}
SQL中UserName和PassWord类型都是 verchar(50)
如果把
string sql = string.Format("insert into tb_User ([UserID],[UserName],[PassWord]) VALUES ({0}, {1},{2})", Convert.ToInt16(tb_ID.Text), tb_Name.Text, tb_Psw.Text);
直接结出string字符串就没问题
string sql = string.Format("insert into tb_User (UserID,UserName,PassWord) VALUES ('3', 'fgfffgfgfg', 'gfgfgfggfgfgfgh')");
这样能通过,但是在textbox中输入字母就不行 展开
代码如下,本人菜鸟,请详解一下症结所在,谢谢指教!
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn = new SqlConnection("Data Source=SQLofVE;Initial Catalog=HIV;Integrated Security=True");
private void GetDataGridView()
{
string sql = "select * from tb_User";
dataGridView1.Columns.Clear();
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataTable table = new DataTable();
sda.Fill(table);
dataGridView1.DataSource = table;
}
private void Form1_Load(object sender, EventArgs e)
{
GetDataGridView();
}
private void btn_add_Click(object sender, EventArgs e)
{
string sql = string.Format("insert into tb_User (UserID,UserName,PassWord) VALUES ({0}, {1},{2})", Convert.ToInt16(tb_ID.Text), tb_Name.Text, tb_Psw.Text); //数字可以通过,为何加字母就出错?
SqlCommand scmd = new SqlCommand(sql, conn);
conn.Open();
try
{
int num = scmd.ExecuteNonQuery();
if (num > 0)
{
GetDataGridView();
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
conn.Close();
}
}
}
SQL中UserName和PassWord类型都是 verchar(50)
如果把
string sql = string.Format("insert into tb_User ([UserID],[UserName],[PassWord]) VALUES ({0}, {1},{2})", Convert.ToInt16(tb_ID.Text), tb_Name.Text, tb_Psw.Text);
直接结出string字符串就没问题
string sql = string.Format("insert into tb_User (UserID,UserName,PassWord) VALUES ('3', 'fgfffgfgfg', 'gfgfgfggfgfgfgh')");
这样能通过,但是在textbox中输入字母就不行 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询