本文介绍了连接属性未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["abc"].ConnectionString);
SqlCommand cmd;


cmd = new SqlCommand("insert into student (name,email,mobile,userid,pass) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')", con);
cmd = new SqlCommand("insert into course (stid) select top (1) stid from student order by stid desc", con);
cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc");
//cmd.CommandType = CommandType.StoredProcedure;

//cmd.Parameters.AddWithValue("@name", textBox1.Text);
//cmd.Parameters.AddWithValue("@email", textBox2.Text);
//cmd.Parameters.AddWithValue("@mobile", textBox3.Text);
//cmd.Parameters.AddWithValue("@userid", textBox4.Text);
//cmd.Parameters.AddWithValue("@pass", textBox5.Text);
//cmd.Parameters.AddWithValue("@username", cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

推荐答案

cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc");



相同的对象在上面的代码中被使用3次。第三次连接属性未传递给命令对象。


same object intilized 3 times in above code.in third time connection property not passed to command object.

cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc");



用以下代码替换此代码。


replace this code with below.

cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc",con);


cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc");



你没有提供con对象。即没有传递给命令对象的连接对象,这就是为什么cmd对象的连接属性未初始化的原因。



你的陈述应该是


you have not provided the con object. ie there is no connection object passed to command object thats why your connection property of cmd object not initialized.

your statement should be

cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc",con);


cmd = new SqlCommand("insert into course (coursename)values ('" + comboBox1.Text + "') select top (1) stid from course order by stid desc", con);



注意:你正在初始化SqlCommand对象3次,你是否正在尝试更多的东西来实现。因为总是最后的初始化语句会起作用。



请使用参数化查询以避免SQL注入。


Note: You are initializing SqlCommand Object 3-times, are you trying anything more to achieve. Because always last initialization statement will work.

Please use parameterized query in order to avoid SQL injection.


这篇关于连接属性未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 10:30
查看更多