i am creating a connection to my database from from visual studio.
this is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class CM : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("server =KIRITI; database =msdb; Integrated Security=True");
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
String NotesMaker = TextBox1.Text;
SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)");
cmd.ExecuteNonQuery();
cmd.CommandText = "Select@@Identity";
con.Close();
}
}
I get an error at command.Executenonquery(): An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteNonQuery: Connection property has not been initialized.
Please help!! I'm blocked from two days!!
Thats the first place where I have seen string concatenation causing conn
to be part of query.
You misplaced string quotes, your statement should be:
SqlCommand cmd =
new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('" + NotesMaker + "'",con);
In your current code, you are passing string "Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)"
, hence the connection property is not initialized and hence the exception.
You should never use string concatenation for creating queries, instead use Parameters. This will save you from SQL Injection . Like:
using(SqlConnection con = new SqlConnection("connectionstring"))
using(SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(@NotesMaker)",con))
{
cmd.Parameters.AddWithValue("@NotesMaker", NotesMaker);
con.Open();
cmd.ExecuteNonQuery();
}
You put con
inside the quotes of the first parameter of the constructor for SqlCommand
, thus the code is complaining because you aren't setting the Connection property of your SqlCommand
change
SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)");
to
SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"')",con);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.