razor - Exception when attempting to connect to SQL Server CE from C# -
i'm newbie trying learn web programming. i'm making site in vs 2012 using c#. i've got database connected in app_data folder, using sql server ce 4.0. i'm attempting connect follows:
sqlcecommand cmd1 = new sqlcecommand("select admin systemusers email=" + user.email); sqlcedatareader admin = null; sqlceconnection conn = new sqlceconnection(); conn.connectionstring = "data source=mydata.sdf;persist security info=false;"; conn.open(); admin = cmd1.executereader();
when execute this, following error:
an exception of type 'system.data.sqlserverce.sqlceexception' occurred in system.data.sqlserverce.dll not handled in user code
any thoughts i'm doing wrong? i've been trying figure out hours.
you said database in app_data directory, connection string assumes in root directory of site.
try
conn.connectionstring = @"data source|datadirectory|\mydata.sdf;persist security info=false;";
the |datadirectory| placeholder string net framework changes predefined location data files supposed stay
and how change code
using(sqlceconnection conn = new sqlceconnection(@"data source|datadirectory|\mydata.sdf;persist security info=false;")) using(sqlcecommand cmd1 = new sqlcecommand("select admin systemusers email=@mail", conn)) { conn.open(); cmd1.parameters.addwithvalue("@mail", user.email); sqlcedatareader admin = cmd1.executereader(); while(admin.read()) { ..... } }
as can see, have made changes:
- added using statement around creation of connection , of command. ensure proper closing , disposing of 2 objects.
- added parameterized query avoid problems in parsing text strings , sql injections
Comments
Post a Comment