Dopo aver aggiunto i riferimenti (dal menu progetti,selezionare aggiungi riferimenti) System.data.Sqlce e System.data , aggiungere i namespace per la gestione dei database.
Di seguito si riportano i namaspace.
VB.Net
Imports System.IO
Imports System.Data.SqlServerCe
Imports System.Data
C#
using System.Data.SqlServerCe;
VB.Net
Private Sub BtnCreaDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCreaDB.Click
Dim conDati As SqlCeConnection
Try
'elimino eventualmente il db creato
System.IO.File.Delete("\My Documents\Miodb.sdf")
Dim SQLEngine As New SqlCeEngine("data source=\My Documents\Miodb.sdf")
SQLEngine.CreateDatabase()
' mi connetto al db
conDati = New SqlCeConnection("Data Source=\My Documents\Miodb.sdf")
conDati.Open()
'Creazione di un tabella
Dim SQL As [String] = "CREATE TABLE MiaTabella (ID int Primary Key " + "NOT NULL,Nome nvarchar(50) NOT NULL)"
Dim cmdDati As New SqlCeCommand(SQL, conDati)
cmdDati.CommandType = CommandType.Text
cmdDati.ExecuteNonQuery()
SQL = ""
'Inserisco i dati
SQL = "INSERT INTO MiaTabella (ID, Nome) VALUES " + "('0','Emanuele')"
cmdDati.CommandText = SQL
cmdDati.ExecuteNonQuery()
SQL = ""
SQL = "INSERT INTO MiaTabella (ID, Nome) VALUES " + "('1','Emanuele2')"
cmdDati.CommandText = SQL
cmdDati.ExecuteNonQuery()
SQL = ""
SQL = "Select * from MiaTabella "
cmdDati.CommandText = SQL
Dim rdrDati As SqlCeDataReader = cmdDati.ExecuteReader()
While rdrDati.Read()
MessageBox.Show(rdrDati.GetString(1))
End While
Catch ex As SqlCeException
MessageBox.Show(ex.Message)
Finally
conDati.Close()
End Try
C#
private void btnCreaDB_Click(object sender, EventArgs e)
{
SqlCeConnection conDati = null;
try
{
//elimino eventualmente il db creato
System.IO.File.Delete(@"\My Documents\Miodb.sdf");
SqlCeEngine SQLEngine = new SqlCeEngine("data source=" + @"\My Documents\Miodb.sdf");
SQLEngine.CreateDatabase();
// mi connetto al db
conDati = new SqlCeConnection("Data Source=" + @"\My Documents\Miodb.sdf");
conDati.Open();
//Creazione di un tabella
string SQL = "CREATE TABLE MiaTabella (ID int Primary Key " + "NOT NULL,Nome nvarchar(50) NOT NULL)";
SqlCeCommand cmdDati = new SqlCeCommand(SQL, conDati);
cmdDati.CommandType = CommandType.Text;
cmdDati.ExecuteNonQuery();
SQL = "";
//Inserisco i dati
SQL = "INSERT INTO MiaTabella (ID, Nome) VALUES " + "('0','Emanuele')";
cmdDati.CommandText = SQL;
cmdDati.ExecuteNonQuery();
SQL = "";
SQL = "INSERT INTO MiaTabella (ID, Nome) VALUES " + "('1','Emanuele2')";
cmdDati.CommandText = SQL;
cmdDati.ExecuteNonQuery();
SQL = "";
SQL = "Select * from MiaTabella ";
cmdDati.CommandText = SQL;
SqlCeDataReader rdrDati = cmdDati.ExecuteReader();
while (rdrDati.Read())
{
MessageBox.Show(rdrDati.GetString(1));
}
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conDati.Close();
}
}
Download
Nessun commento:
Posta un commento