ExecuteNonQuery 要求已打开且可用的连接。连接的当前状态为已关闭
各位大师代码如下:该怎么解决丫
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace Command { public partial class Form1 : Form { conection comm = new conection(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { label1.Text = "Name";//名字 label2.Text = "Unit";//单位 label3.Text = "Sex";//性别 label4.Text = "Age";//年龄 label5.Text = "Race";//种族 label6.Text = "Url";//网址 dataGridView1.DataSource = XianShiShuJu(); } public DataTable XianShiShuJu() { comm.com().Open(); DataSet ds = new DataSet("数据集1"); DataTable dt = new DataTable("数据表1"); SqlDataAdapter da = new SqlDataAdapter("select * from Staff", comm.com()); ds.Tables.Add(dt); da.Fill(dt); comm.com().Close(); return dt; } private void button1_Click(object sender, EventArgs e) { try { string Mycom = "insert Staff(Name,Unit,Sex,Age,Race,Url) values ("" + textBox1.Text + "","" + textBox2.Text + "","" + textBox3.Text + ""," + Convert.ToInt32(textBox4.Text) + ","" + textBox6.Text + "","" + textBox7.Text + """; SqlCommand com = new SqlCommand(Mycom, comm.com()); comm.com().Open(); using (comm.com()) { com.ExecuteNonQuery(); MessageBox.Show("添加成功","数据保存"); textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); textBox6.Clear(); textBox7.Clear(); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } comm.com().Close(); } private void button2_Click(object sender, EventArgs e) { dataGridView1.DataSource = this.XianShiShuJu(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace Command { class conection { public SqlConnection com() { string Mycon = "server = XQ-20160210KQLE\SA;uid = sa;pwd = 123456;database = JYXinXi"; SqlConnection con = new SqlConnection(Mycon); return con; } } }
解决方案
10
SqlConnection con = new SqlConnection(Mycon);
con.Open();
con.Open();
20
题主你能不能把comm.com()的结果存起来, 不要调用那么多次, 每次都产生一个新的连接这样不对.