Publicada aplicación AjpdSoft Acceso SQLite C# ADO.NET y código fuente gratuito en C#. Mostramos en este artículo cómo funciona la aplicación y un listado del código completo.
- Videotutorial AjpdSoft Acceso SQLite.
- Acceso a SQLite usando el lenguaje de programación C# y ADO.NET.
- AjpdSoft Acceso SQLite C# ADO.NET en funcionamiento.
- Código fuente completo de AjpdSoft Acceso SQLite C# ADO.NET.
Videotutorial AjpdSoft Acceso SQLite
A continuación mostramos un videotutorial sobre AjpdSoft Acceso SQLite C# ADO.NET con su funcionamiento básico para administración y gestión de bases de datos SQLite:
Acceso a SQLite usando el lenguaje de programación C# y ADO.NET
En el siguiente enlace mostramos un tutorial que explica paso a paso cómo crear una solución en Microsoft Visual Studio .Net 2012 con Visual C# .Net que accede y trabaja con bases de datos SQLite (uando ADO.NET):
AjpdSoft Acceso SQLite C# ADO.NET en funcionamiento
La aplicación AjpdSoft Acceso SQLite C# ADO.NET permite conectarse de forma nativa (mediante ADO.NET) a un fichero de base de datos SQLite. La aplicación incluye las siguientes funcionalidades:
- Crea ficheros de bases de datos SQLite.
- Abre ficheros de bases de datos SQLite existentes.
- Permite abrir y crear ficheros de bases de datos SQLite con contraseña.
- Ejecuta consultas SQL definidas por el usuario contra el fichero SQLite, tanto consultas de selección (SELECT, GROUP, HAVING), como de modificación (INSERT, UPDATE, DELETE, DROP, ALTER).
- Muestra el resultado de la ejecución de consultas SQL de selección en pantalla.
- Permite exportar el resultado de consultas SQL de selección a fichero CSV.
Para crear un fichero de base de datos SQLite introduciremos la carpeta y nombre del fichero, introduciremos la contraseña (si queremos establecer seguridad al fichero SQLite), marcaremos «Crear base de datos si no existe». Pulsando en el botón «Abrir/Crear BD» la aplicación creará y abrirá la bd y mostrará un mensaje indicando «BD SQLite abierta correctamente. Número de tablas que contiene: 0» (obviamente aún no contendrá ninguna tabla pues acabamos de crearla):
Ahora podremos trabajar con el fichero creado, por ejemplo, para crear una nueva tabla introduciremos en «SQL»:
create table prueba (codigo int, nombre varchar(100))
Puesto que es una consulta SQL de modificación de datos desmarcaremos «Devuelve datos» y pulsaremos en «Ejecutar consulta SQL»:
Insertaremos varios registros en la tabla de prueba con el SQL:
insert into prueba values (1, «AjpdSoft»)
Y como test podremos mostrar los registros insertados, con el SQL:
select * from prueba
Marcando la opción «Devuelve datos» y pulsando en «Ejecutar consulta SQL». Si todo es correcto mostrará los registros insertados en la tabla «prueba» en el grid datos:
Para exportar los datos mostrados a un fichero CSV pulsaremos en el botón «E», nos mostrará una ventana para indicar la carpeta y nombre del fichero donde exportaremos los datos, por ejemplo «datos_sqlite.csv»:
Una vez exportado podremos abrir el fichero CSV con cualquier aplicación compatible (Microsoft Excel, Libre Office Calc, etc.):
Por supuesto, AjpdSoft Acceso SQLite C# ADO.NET permite abrir ficheros de base de datos SQLite existentes ya creados con otras aplicaciones o incluso BDs de Android.
Código fuente completo de AjpdSoft Acceso SQLite C# ADO.NET
A continuación listamos el código fuente completo de la aplicación AjpdSoft Acceso SQLite C# ADO.NET:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SQLite; namespace AjpdSoftAccesoSQLiteCSharp { public partial class formAccesoSQLiteCSharp : Form { private SQLiteConnection conexionSQLite; private List obtenerTablasBDSQLite() { List listaTablasSQLite = new List(); string consultaSQL = "select name from sqlite_master where type = 'table'"; SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; try { SQLiteDataReader sqlReader = comandoSQL.ExecuteReader(); while (sqlReader.Read()) { listaTablasSQLite.Add(sqlReader.GetString(0)); } comandoSQL.Dispose(); sqlReader.Dispose(); return listaTablasSQLite; } catch (Exception error) { MessageBox.Show("Error al obtener el nombre de las tablas. " + "Error: " + error.Message, "Error tablas BD SQLite", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return listaTablasSQLite; } } private long obtenerNumeroTablasBDSQLite () { string consultaSQL = "select count(*) from sqlite_master where type = 'table'"; SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; try { long numeroTablas = (long)comandoSQL.ExecuteScalar(); comandoSQL.Dispose(); return numeroTablas; } catch (Exception error) { MessageBox.Show("Error al obtener el número de tablas. " + "Error: " + error.Message, "Error nº tablas BD SQLite", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return -1; } } public formAccesoSQLiteCSharp() { InitializeComponent(); } private void btAbrirBDSQLite_Click(object sender, EventArgs e) { if (txtBDSQLite.Text != "") { if ((opCrearBD.Checked)) { if (!System.IO.File.Exists(txtBDSQLite.Text)) { try { SQLiteConnection.CreateFile(txtBDSQLite.Text); } catch (Exception error) { MessageBox.Show("Error al crear la BD SQLite. " + "Error: " + error.Message, "Error al crear BD SQLite", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } //Abrir bd if (System.IO.File.Exists(txtBDSQLite.Text)) { string stringConexionSQLite = String.Format("Data Source={0}", txtBDSQLite.Text); try { conexionSQLite = new SQLiteConnection(stringConexionSQLite); if (txtContrasena.Text != "") { conexionSQLite.SetPassword(txtContrasena.Text); } conexionSQLite.Open(); long numeroTablas = obtenerNumeroTablasBDSQLite(); if (numeroTablas == -1) { MessageBox.Show("Ha habido algún error al " + "intentar obtener el número de tablas de " + "la BD SQLite.", "Error al obtener nº tablas", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //obtener el nombre de las tablas lsTablas.DataSource = obtenerTablasBDSQLite(); MessageBox.Show("BD SQLite abierta correctamente. " + "Número de tablas que contiene: " + Convert.ToString(numeroTablas), "BD abierta", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception error) { MessageBox.Show("Error al abrir la BD SQLite. " + "Error: " + error.Message, "Error al abrir BD SQLite", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } else { MessageBox.Show("Es necesario especificar una carpeta y " + "fichero SQLite a abrir/crear.", "Fichero SQLite no indicado", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); txtBDSQLite.Focus(); } } private void btEjecutarSQL_Click(object sender, EventArgs e) { if (opSQLDevuelveDatos.Checked) { DataTable dt = new DataTable(); SQLiteDataAdapter DataAdapter; try { string consultaSQL = txtSQL.Text; SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; DataAdapter = new SQLiteDataAdapter(comandoSQL); DataAdapter.Fill(dt); dbTabla.DataSource = dt; } catch (Exception error) { MessageBox.Show("Error al ejecutar SQL: " + error.Message, "Error SQL", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { string consultaSQL = txtSQL.Text; SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; int numRegistrosAfectados = 0; numRegistrosAfectados = comandoSQL.ExecuteNonQuery(); MessageBox.Show("Consulta SQL de modificación ejecutada correctamente. " + "Número de registros afectados: " + Convert.ToString(numRegistrosAfectados), "Ejecutada SQL modificación", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception error) { MessageBox.Show("Error al ejecutar SQL: " + error.Message, "Error SQL", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btSelBDSQLite_Click(object sender, EventArgs e) { dlAbrir.CheckFileExists = false; dlAbrir.CheckPathExists = true; dlAbrir.Multiselect = false; dlAbrir.DefaultExt = "sqlite"; dlAbrir.FileName = ""; dlAbrir.Filter = "Archivos SQLite (*.sqlite)|*.sqlite|" + "Todos los archivos (*.*)|*.*"; dlAbrir.Title = "Seleccionar fichero BD SQLite a abrir"; if (dlAbrir.ShowDialog() == DialogResult.OK) { txtBDSQLite.Text = dlAbrir.FileName; } } private void btSelectTabla_Click(object sender, EventArgs e) { txtSQL.Text = "select * from " + lsTablas.Text; } private void btCambiarContrasena_Click(object sender, EventArgs e) { try { conexionSQLite.ChangePassword(txtNuevaContrasena.Text); MessageBox.Show("Contraseña cambiada correctamente.", "Contraseña cambiada", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception error) { MessageBox.Show("Error al cambiar la contraseña: " + error.Message, "Error al cambiar la contraseña", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btExportarCSV_Click(object sender, EventArgs e) { dlGuardar.Filter = "Fichero CSV (*.csv)|*.csv"; dlGuardar.FileName = "Datos_sqlite"; dlGuardar.Title = "Exportar a CSV"; if (dlGuardar.ShowDialog() == DialogResult.OK) { StringBuilder csvMemoria = new StringBuilder(); //para los títulos de las columnas, encabezado for (int i = 0; i < dbTabla.Columns.Count; i++) { if (i == dbTabla.Columns.Count - 1) { csvMemoria.Append(String.Format(""{0}"", dbTabla.Columns[i].HeaderText)); } else { csvMemoria.Append(String.Format(""{0}";", dbTabla.Columns[i].HeaderText)); } } csvMemoria.AppendLine(); for (int m = 0; m < dbTabla.Rows.Count; m++) { for (int n = 0; n < dbTabla.Columns.Count; n++) { //si es la última columna no poner el ; if (n == dbTabla.Columns.Count - 1) { csvMemoria.Append(String.Format(""{0}"", dbTabla.Rows[m].Cells[n].Value)); } else { csvMemoria.Append(String.Format(""{0}";", dbTabla.Rows[m].Cells[n].Value)); } } csvMemoria.AppendLine(); } System.IO.StreamWriter sw = new System.IO.StreamWriter(dlGuardar.FileName, false, System.Text.Encoding.Default); sw.Write(csvMemoria.ToString()); sw.Close(); } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //abrir navegador por defecto y acceder a la URL proyectoa.com System.Diagnostics.Process.Start("https://proyectoa.com"); } } } |