急!!c# 数据库连接上了,为什么向里面添加记录时添加不进去了?

xingtaineiqiu 2009-09-23 05:28:38
我在向数据库里添加记录时添加不进去,以下是我的代码。哪位能看看问题出在哪啊?谢谢了。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 学生管理系统
{
public partial class FrmGuanli : Form
{
private System.Data.SqlClient.SqlConnection conn;
private System.Data.SqlClient.SqlCommand da;
public FrmGuanli()
{
InitializeComponent();
}

private void btnAdd_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("所有项都必须填写!","信息框");
return;
}
string str="Persist Security Info=False;Initial Catalog=student;";
str+="Data Source=localhost;Integrated Security=SSPI;";
string str1="insert into student(studentID,studentName,studentSex)Values('";
str1+=textBox1.Text+"','";
str1+=textBox2.Text+"','";
str1+=textBox3.Text+"')";
try
{
conn = new SqlConnection(str);
conn.Open();//打开数据库连接
da = new SqlCommand(str1, conn);
da.ExecuteNonQuery();//执行SQL语句
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
conn.Close();
}
catch (SqlException oe)
{
MessageBox.Show(oe.Message,"Error");
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}
}
...全文
148 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xray2005 2009-09-23
  • 打赏
  • 举报
回复

private void btnAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text.Trim()) || string.IsNullOrEmpty(textBox2.Text.Trim()) || string.IsNullOrEmpty(textBox3.Text.Trim()))
{
MessageBox.Show("所有项都必须填写!","信息框");
return;
}
string str="Persist Security Info=False;Initial Catalog=student;Data Source=localhost;Integrated Security=SSPI;";
string str1="insert into student(studentID,studentName,studentSex)Values(@id,@name,@sex)";

try
{
conn = new SqlConnection(str);
conn.Open();//打开数据库连接
da= new SqlCommand(str1, conn);
da.Parameters.Add("@id",SqlDbType.VarChar).Value=textBox1.Text.Trim();
da.Parameters.Add("@name",SqlDbType.VarChar).Value=textBox2.Text.Trim();
da.Parameters.Add("@sex",SqlDbType.VarChar).Value=textBox3.Text.Trim();
da.ExecuteNonQuery();//执行SQL语句
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
conn.Close();
}
catch (SqlException oe)
{
MessageBox.Show(oe.Message,"Error");
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}

xingfei2010 2009-09-23
  • 打赏
  • 举报
回复
呵呵,我感觉没啥问题啊
moodlog 2009-09-23
  • 打赏
  • 举报
回复
写代码的习惯不好,命名空间都写出来了,怎么还 System.Data.SqlClient.SqlConnection,你直接写 SqlConnection 就可以了,代码基本没什么问题,不知道你的表名,是否正确。
haohaoxuexihere 2009-09-23
  • 打赏
  • 举报
回复
同楼上的 报的什么错啊..有么调试过..
还想懒够 2009-09-23
  • 打赏
  • 举报
回复
报啥错?

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧