first time I'm doing an insert from ASP.NET/C# and I'm having a little issue. I keep getting the following error every time this code runs: " ExecuteNonQuery: CommandText property has not been initialized" Does anyone know what this means and how I fix it?
Thanks in advance!
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += "VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = dataConnection.CreateCommand())
{
dataConnection.Open();
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
dataCommand.Parameters.Add("#Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Rep", repID);
dataCommand.Parameters.Add("#Reason", txtReason.Text);
dataCommand.Parameters.Add("#Contact", txtContact.Text);
dataCommand.Parameters.Add("#CaseNum", txtCaseNum.Text);
dataCommand.Parameters.Add("#Comments", txtComments.Text);
dataCommand.Parameters.Add("#PropertyID", lstProperties.SelectedValue);
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += " VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection))
{
dataCommand.Parameters.AddWithValue("Today", DateTime.Today.ToString());
dataCommand.Parameters.AddWithValue("Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Rep", repID);
dataCommand.Parameters.AddWithValue("Reason", txtReason.Text);
dataCommand.Parameters.AddWithValue("Contact", txtContact.Text);
dataCommand.Parameters.AddWithValue("CaseNum", txtCaseNum.Text);
dataCommand.Parameters.AddWithValue("Comments", txtComments.Text);
dataCommand.Parameters.AddWithValue("PropertyID", lstProperties.SelectedValue);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
Copy-paste should do the trick
This usually means you haven't set the CommandText property, but in your case, you have.
You should try testing that the sqlQuery string is actually not empty at this line:
dataCommand.CommandText = sqlQuery;
P.S. As a "best practice", you may want to consider opening the connection AFTER setting up the SqlCommand object, to minimize the time spent with an open connection:
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
//...
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
Looking at your string sql query, you're not leaving a space between the "INTO" part and "VALUES" part.
...............Property_ID)";
sqlQuery += "VALUES (#Today, ..............
SHOULD BE:
...............Property_ID)";
sqlQuery += " VALUES (#Today, ..............
Related
I was gonna save my date and time record in my database when an unhandled exception always thrown at this code: int value = cmd.ExecuteNonQuery(); when I'm clicking the 'Time In' button.
it says that MySql.Data.MySqlClient.MySqlException 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Mar 2022 3:53:00 AM,System.Windows.Forms.DateTimePicker, Value
When I check my codes, there's no errors. I debugged it but no errors appeared.
Here's my codes:
private void btnTimeIn_Click(object sender, EventArgs e)
{
string connectstring = "datasource=localhost;port=3306;username=root;password=;database=employeedb;SslMode=none";
MySqlConnection conn = new MySqlConnection(connectstring);
conn.Open();
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
MySqlCommand cmd = new MySqlCommand(iQuery, conn);
int value = cmd.ExecuteNonQuery();
MessageBox.Show(value.ToString());
conn.Close();
}
Your immediate help, tips and advice are highly appreciated
I was gonna expect that I'm gonna save records in my database by timing in... but I can't even find what could be wrong because i just did all ways of inserting data into table in database. Still, I didn't also work, and the exception still throwing every time at the 'cmd.ExecuteNonQuery' line.
This line of code is causing the bug, and can also lead to SQL injection:
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
You should always use command parameters, not string concatenation:
using (MySqlConnection conn = new MySqlConnection(connectstring))
{
conn.Open();
string iQuery = #"
INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`,
`RecordDate`, `TimeIn`, `TimeOut`)
VALUES (#id, #last, #first, #date, #in, #out);";
using MySqlCommand cmd = new MySqlCommand(iQuery, conn))
{
cmd.Parameters.AddWithValue("#id", txtEmployeeID.Text);
cmd.Parameters.AddWithValue("#first", txtLstName.Text);
cmd.Parameters.AddWithValue("#last", txtFirstName.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#in", dateTimePicker2.Value);
cmd.Parameters.AddWithValue("#out", dateTimePicker3.Value);
int value = cmd.ExecuteNonQuery();
}
}
Additionally, use using statements to automatically close and clean up database resources.
I'm trying to execute 2 query in one button click.. It doesn't seem to work and just closes automatically. Can anyone help me or explain to me why my code doesn't work? Here's the code:
test = 1;
{
connection.Open();
string strTemp = " [StudentNum] Text, [StudentName] Text, [Section] Text, [TimeIn] Text, [TimeOut] Text, [Status] Text";
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = connection;
myCommand.CommandText = "CREATE TABLE [" + date + "](" + strTemp + ")";
myCommand.ExecuteNonQuery();
if (test == 1)
{
OleDbCommand commandl = new OleDbCommand();
commandl.Connection = connection;
commandl.CommandText = "INSERT INTO ['" + date + "']([StudentNum],[StudentName],[Section]) select [StudentNo],[Name],[Section] from StudInfo";
commandl.ExecuteNonQuery();
}
Remove the apostrophes delimiting table name.
commandl.CommandText = "INSERT INTO [" + date + "]([StudentNum],[StudentName],[Section]) select [StudentNo],[Name],[Section] from StudInfo";
I'm stuck on a issue where I need to backup my database via Winforms. I managed to find a sample SQL code in order to achieve this task.
My query here :
SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True");
Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
I have no idea how to proceed next. What should I use in this scenario? (ExecuteScalar, ExecuteNonQuery..etc)
Any help would be appreciated.
Note that Date time is also there in back up file name.
You define the SQL command to execute, and then instantiate a SqlCommand. Since the SQL statement isn't expected to return any data (a result set etc.), use ExecuteNonQuery:
string Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
using(SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True"))
using(SqlCommand cmdBackup = new SqlCommand(Sql, CON))
{
// open connection, execute command, close connection
CON.Open();
cmdBackup.ExecuteNonQuery();
CON.Close();
}
The general code:
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var comm = conn.CreateCommand())
{
comm.CommandType = CommandType.Text;
comm.CommandText = "BACKUP DATABASE...";
comm.ExecuteNonQuery();
}
}
I'm trying to execute multiple updates like this
UPDATE clients SET name = :name WHERE clientId = :clientID
I've tried something like this
OracleConnection con = new OracleConnection(connectionString);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText =
"begin " +
" UPDATE clients SET name = " + name1 + " WHERE clientId = " + clientId1 +
" UPDATE clients SET name = " + name2 + " WHERE clientId = " + clientId2 +
"end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
but I need to execute hundreds of parameterized updates like the first one
I am connecting to a compact SQL database server through a WCF service and keep getting the following except on the Command.ExecuteNonQuery(). I have tried fixing this but just don't know what's wrong.
The exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred
in System.Data.SqlServerCe.dll but was not handled in user code
The code:
//The connectionString can be found in the properties table of the database
string connString = "Data Source=C:\\Users\\User\\documents\\visual studio 2012\\Projects\\ADO_LINQ\\ADO_LINQ\\App_Data\\MyDatabase.sdf;Persist Security Info = False";
SqlCeConnection myConnection = new SqlCeConnection(connString);
myConnection.Open();
// Create the query
string myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + "," +
firstName + ", " +
lastName + ", " +
phoneNumber + ", " +
address + ", " +
dateOfBirth + ");";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
//Run the command
myCommand.ExecuteNonQuery();
//Close the connection
myConnection.Close();
You are missing Single quotes around your string data types, Assuming only registrationID is Integer data type and all other columns are String data type , your query should look something like ......
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + ", '"+ firstName +"' , '"+lastName+"' , '"+phoneNumber+ "', '"+ address +"', '"+dateOfBirth+"' );";
A better and safer option would be to use Parametrised query. Something like this.....
String connString = #"Data Source=C:\Users\User\documents\visual studio 2012\Projects\ADO_LINQ\ADO_LINQ\App_Data\MyDatabase.sdf;Persist Security Info = False";
using(SqlCeConnection myConnection = new SqlCeConnection(connString))
{
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (#registrationID , #firstName , #lastName , #phoneNumber, #address , #dateOfBirth );";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
// Add parameters
myCommand.Parameters.AddWithValue("#registrationID" ,registrationID);
myCommand.Parameters.AddWithValue("#firstName" , firstName);
myCommand.Parameters.AddWithValue("#lastName" , lastName);
myCommand.Parameters.AddWithValue("#phoneNumber" , phoneNumber);
myCommand.Parameters.AddWithValue("#address" , address);
myCommand.Parameters.AddWithValue("#dateOfBirth" , dateOfBirth);
//Open Connection
myConnection.Open();
//Run the command
myCommand.ExecuteNonQuery();
}