Im testing out some database compact code using a simple form to add data to a database.
When I click the AddBtn, all I want is to insert some values from text fields into my database but instead I get this error “Format of the initialization string does not conform to specification starting at index 0.” And the problem seems to be within the SqlCeConnection row.
Complete code sample:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void AddBtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(@"C:\Users\Name\Documents\Visual Studio 2012\Projects\DataBaseTest\MyDatabase#1.sdf");
try {
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "insert into test ([ID], [OrderID], [KundID]) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"')";
try {
cmd.ExecuteNonQuery();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
You are not using a valid connection string (add
'Data Source='before the path to the SDF.See the MSDN documentation for
SqlCeConnection.Other than that do not use the text of the buttons directly in the query (leaves you open to SQL injection attack) use SQL parameters instead (again MSDN is your friend.)