Cornelis
Cornelis

Reputation: 1107

SqlCeCommand keeps giving me an exception

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

Upvotes: 0

Views: 63

Answers (1)

M.Ali
M.Ali

Reputation: 69554

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

Upvotes: 3

Related Questions