SqlCeCommand keeps giving me an exception - c#

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();
}

Related

Exception Unhandled - MySql.Data.MySqlClient.MySqlException

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.

C# SQL insert query syntax error with MS Access

I am trying to perform an insert query in C# but it keeps telling me syntax error in insert into statement.
Here is my query:
Checks.SQL.Insert(mydb, "SELECT * FROM Employee", "INSERT INTO Employee(First_Name,Last_Name,Email,CellPhone_Number,TypeOfUser,Username,Password) VALUES('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + " ', '" + txtCellphone.Text + "'," + typeId + ",'"+Encrypcion.encrypt(txtUsername.Text)+"','"+Encrypcion.encrypt(txtPassword.Text)+"' )");
Here is my checks insert function
public static void Insert(OleDbConnection mydb, string SelectQuery, string InsertQuery)
{
mydb.Open();
OleDbDataAdapter query2 = new OleDbDataAdapter(SelectQuery, mydb);
OleDbCommand cmd = new OleDbCommand(InsertQuery, mydb);
query2.InsertCommand = cmd;
query2.InsertCommand.ExecuteNonQuery();
mydb.Close();
}
Here is a picture of my InsertQuery with input data as example:
enter image description here
See a picture of my table info:
Password is a reserved word in Access, so:
"INSERT INTO Employee(First_Name,Last_Name,Email,CellPhone_Number,TypeOfUser,Username,[Password]) .."

mysql command executescalar returns null in C#

Let's say I have a query result that looks as follows:
ID NAME Phone
---- ---- -----
1 John 123456
2 John 125678
3 John 345678
4 Abby 456789
5 Abby 567890
I want to return just a single row instance of name: John, where the phone number like '12%'.
In c#, I wrote this syntax to get the PersonName variable as the result of the query.
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
connection.Close();
I don't know whats wrong with my code but the PersonName returns null. What did I do wrong?
We have to be missing something else here. Try the following code sample based on what you provided:
try {
MySqlConnection connection = new MySqlConnection("SERVER=localhost;DATABASE=testdb;UID=root;PASSWORD=;");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
finally {
connection.Close();
}
I have a feeling that for some reason the call to .Open() is failing and the error is being swallowed elsewhere. Try the above and let me know what you find out.
do this : change this (string)command.ExecuteScalar(); by Convert.ToString(command.ExecuteScalar());
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = Convert.ToString(command.ExecuteScalar());
connection.Close();

C# MySQL retrieving a value from a column matching another

So I have a table with the following columns:
ID, name, adress, etc..
I have been doing some research but I cannot come across the right keywords to find out to do what I want. I would like to be able to take the name value (Which would be say... "John Doe" which is in the database already for sure..) and retrieve the ID of it (from the int MySQL value ID).
I have come across the following code but I cannot seem to figure out how to extend its limits to match my needs.
connection2.Open();
cmd.ExecuteNonQuery();
try
{
MySqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(myReader.GetOrdinal("id")));
}
myReader.Close();
}
finally
{
connection2.Close();
}
This is also what I have come up with to the best of my abilities.
MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";");
string query = #"SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
MySqlCommand cmd = new MySqlCommand(query, connection2);
You should replace the hard coded parameters with sql parameters, but here is a general idea of what you'll need to do here. Using your present sql query.
MySqlConnection sqlConn = new MySqlConnection();
MySqlCommand sqlCmd = new MySqlCommand();
string sSql = "SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
sqlConn.ConnectionString = "Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";";
sqlCmd.CommandText = sSql;
sqlCmd.CommandType = CommandType.Text;
sqlConn.Open();
sqlCmd.Connection = sqlConn;
MySqlDataReader reader = sqlCmd.ExecuteReader();
List<string> results = new List<string>();
while (reader.Read())
{
results.Add((reader["id"].ToString());
}
reader.Close();
sqlConn.Close();
Keep in mind you can add the reader results to a string, to a list like above, whatever you want to do with it.
this how id en name pawe
clsMySQL.sql_con.Open();
string id = ID;
sql = "SELECT *FROM test";
cmd = new MySqlCommand(sql, clsMySQL.sql_con);
sql_cmd = new MySqlCommand(sql, clsMySQL.sql_con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr["id"].ToString();
user = dr["user_name"].ToString();
pass = dr["password"].ToString();
if (name.Text == user && passw.Text == pass)
{
string depart = id;
Hide();
MessageBox.Show("it works");
// Then show the main form
cracker form = new cracker(name.Text);
form.sid = depart;
form.Show();
MessageBox.Show(ID);
}
}
else
{
MessageBox.Show("Invalid Login please check username and password");
}
clsMySQL.sql_con.Close();
}

C# Database Insert (ASP.NET) - ExecuteNonQuery: CommandText property has not been initialized

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, ..............

Categories

Resources