Olá Pessoal.
Neste artigo eu vou falar sobre um banco de dados embarcado que eu acho muito prático de usar o nome dele é SQLite.
O que é o SQLite?
SQLite é uma biblioteca C que implementa um banco de dados SQL embutido. Programas que usam a biblioteca SQLite podem ter acesso ao banco de dados SQL sem executar um processo RDBMS separado.
SQLite não é uma biblioteca de cliente usada para conectar com um grande servidor de banco de dados. SQLite é o servidor.
A biblioteca SQLite lê e escreve diretamente para e do arquivo do banco de dados no disco.
O uso do SQLite é recomendado onde a simplicidade da administração, implementação e manutenção são mais importantes que incontáveis recursos que SGBDs mais voltados para aplicações complexas possivelmente implementam.
Entretanto situações onde a simplicidade é a melhor escolha são muito mais freqüentes do que pode-se imaginar.
Exemplos de uso do SQLite são:
- Não restrito à sites (com menos de cem mil requisições por dia);
- Dispositivos e sistemas embarcados;
- Aplicações desktop;
- Ferramentas estatísticas e de análise;
- Aprendizado de banco de dados;
- Implementação de novas extensões à SQL.
Não se recomenda o uso do SQLite para:
- Sites com muitos acessos;
- Grande quantidades de dados (talvez maior que algumas dúzias de gigabytes);
- Sistemas com grande concorrência;
- Aplicações cliente/servidor.
Algumas características do SQLite:
- Software livre/domínio público e Multiplataforma;
- Mecanismo de armazenamento seguro com transações ACID;
- Não necessita de instalação, configuração ou administração;
- Implementa a maioria do SQL92;
- O Banco de Dados é guardado em um único arquivo;
- Suporta bases de dados acima de 2 terabytes;
- Sem dependências externas.
No artigo irei criar a base de dados e as tabelas “Programaticamente” (não achei uma palavra melhor para descrever isso.) mas se você quiser usar uma ferramenta recomendo o uso do SQLite Studio, é gratuita (http://sqlitestudio.one.pl/index.rvt)
Vou assumir que você já sabe o que é uma base de dados embarcada (embedded, embutido) e que tenha conhecimentos em C#.
Primeiramente temos que preparar o nosso ambiente. Para isso iremos fazer o download do provider para .NET. Descompacte o arquivo em uma pasta, iremos usar este caminho mais tarde.
Feito o download iremos criar um novo projeto do tipo windows form e chamar de SQLiteEmbedded.
Renomearemos o form1 para frmMain.
Vamos colocar seis botões em nosso form, segue os nomes e o texto para cada botão
Nome Botão | Texto |
btnCriarBase | Criar Base |
btnCriarTabelas | Criar Tabelas |
btnInsert | Insert |
btnUpdate | Update |
btnSelect | Select |
btnDelete | Delete |
Com estes botões iremos implementar as operações básicas, desde a criação da base de dados, criação das tabelas e a manipulação dos dados.
Iremos colocar agora um dataGridView e alguns campos de texto e data para montar o nosso form, não se preocupe com o form, ao final do artigo terá um link para download do projeto. Mas se quiser fazer o form.
A tela do meu form ficou assim:
Se quiser poupar trabalho, segue o código para colar no designer (frmMain.Designer.cs) troque o código que tem lá, por este.
namespace SQLiteEmbedded { partial class frmMain { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// <param name="disposing" />true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.btnCriarBase = new System.Windows.Forms.Button(); this.btnCriarTabelas = new System.Windows.Forms.Button(); this.btnInsert = new System.Windows.Forms.Button(); this.Update = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.label1 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtNome = new System.Windows.Forms.TextBox(); this.txtTelefone = new System.Windows.Forms.TextBox(); this.dtDataNascimento = new System.Windows.Forms.DateTimePicker(); this.btnSelect = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); // // btnCriarBase // this.btnCriarBase.Location = new System.Drawing.Point(12, 12); this.btnCriarBase.Name = "btnCriarBase"; this.btnCriarBase.Size = new System.Drawing.Size(103, 23); this.btnCriarBase.TabIndex = 0; this.btnCriarBase.Text = "Criar Base"; this.btnCriarBase.UseVisualStyleBackColor = true; this.btnCriarBase.Click += new System.EventHandler(this.btnCriarBase_Click); // // btnCriarTabelas // this.btnCriarTabelas.Location = new System.Drawing.Point(121, 12); this.btnCriarTabelas.Name = "btnCriarTabelas"; this.btnCriarTabelas.Size = new System.Drawing.Size(103, 23); this.btnCriarTabelas.TabIndex = 1; this.btnCriarTabelas.Text = "Criar Tabelas"; this.btnCriarTabelas.UseVisualStyleBackColor = true; this.btnCriarTabelas.Click += new System.EventHandler(this.btnCriarTabelas_Click); // // btnInsert // this.btnInsert.Location = new System.Drawing.Point(348, 51); this.btnInsert.Name = "btnInsert"; this.btnInsert.Size = new System.Drawing.Size(75, 23); this.btnInsert.TabIndex = 2; this.btnInsert.Text = "Insert"; this.btnInsert.UseVisualStyleBackColor = true; this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click); // // Update // this.Update.Location = new System.Drawing.Point(348, 81); this.Update.Name = "Update"; this.Update.Size = new System.Drawing.Size(75, 23); this.Update.TabIndex = 3; this.Update.Text = "Update"; this.Update.UseVisualStyleBackColor = true; this.Update.Click += new System.EventHandler(this.Update_Click); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(348, 111); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(75, 23); this.btnDelete.TabIndex = 4; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // dataGridView // this.dataGridView.AllowUserToAddRows = false; this.dataGridView.AllowUserToDeleteRows = false; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.Location = new System.Drawing.Point(12, 182); this.dataGridView.Name = "dataGridView"; this.dataGridView.ReadOnly = true; this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView.Size = new System.Drawing.Size(537, 267); this.dataGridView.TabIndex = 6; this.dataGridView.SelectionChanged += new System.EventHandler(this.dataGridView_SelectionChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 51); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(21, 13); this.label1.TabIndex = 7; this.label1.Text = "ID:"; // // txtID // this.txtID.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtID.Location = new System.Drawing.Point(96, 51); this.txtID.Name = "txtID"; this.txtID.ReadOnly = true; this.txtID.Size = new System.Drawing.Size(100, 20); this.txtID.TabIndex = 8; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 81); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(38, 13); this.label2.TabIndex = 9; this.label2.Text = "Nome:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 111); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(52, 13); this.label3.TabIndex = 10; this.label3.Text = "Telefone:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(12, 141); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(70, 13); this.label4.TabIndex = 11; this.label4.Text = "Data Nascto:"; // // txtNome // this.txtNome.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtNome.Location = new System.Drawing.Point(96, 81); this.txtNome.Name = "txtNome"; this.txtNome.Size = new System.Drawing.Size(209, 20); this.txtNome.TabIndex = 12; // // txtTelefone // this.txtTelefone.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtTelefone.Location = new System.Drawing.Point(96, 111); this.txtTelefone.Name = "txtTelefone"; this.txtTelefone.Size = new System.Drawing.Size(94, 20); this.txtTelefone.TabIndex = 13; // // dtDataNascimento // this.dtDataNascimento.CustomFormat = "dd/MM/yyyy"; this.dtDataNascimento.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dtDataNascimento.Location = new System.Drawing.Point(96, 141); this.dtDataNascimento.Name = "dtDataNascimento"; this.dtDataNascimento.Size = new System.Drawing.Size(94, 20); this.dtDataNascimento.TabIndex = 14; // // btnSelect // this.btnSelect.Location = new System.Drawing.Point(348, 140); this.btnSelect.Name = "btnSelect"; this.btnSelect.Size = new System.Drawing.Size(75, 23); this.btnSelect.TabIndex = 15; this.btnSelect.Text = "Select"; this.btnSelect.UseVisualStyleBackColor = true; this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(12, 35); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(538, 13); this.label5.TabIndex = 16; this.label5.Text = "---------------------------------------------------------------------------------" + "--------------------------------------------------------------------------------" + "----------------"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(12, 166); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(538, 13); this.label6.TabIndex = 17; this.label6.Text = "---------------------------------------------------------------------------------" + "--------------------------------------------------------------------------------" + "----------------"; // // frmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(561, 461); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.btnSelect); this.Controls.Add(this.dtDataNascimento); this.Controls.Add(this.txtTelefone); this.Controls.Add(this.txtNome); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.txtID); this.Controls.Add(this.label1); this.Controls.Add(this.dataGridView); this.Controls.Add(this.btnDelete); this.Controls.Add(this.Update); this.Controls.Add(this.btnInsert); this.Controls.Add(this.btnCriarTabelas); this.Controls.Add(this.btnCriarBase); this.Name = "frmMain"; this.Text = "SQLite Embededd"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnCriarBase; private System.Windows.Forms.Button btnCriarTabelas; private System.Windows.Forms.Button btnInsert; private System.Windows.Forms.Button Update; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.DataGridView dataGridView; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtNome; private System.Windows.Forms.TextBox txtTelefone; private System.Windows.Forms.DateTimePicker dtDataNascimento; private System.Windows.Forms.Button btnSelect; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; } }
Ok! Feito isso iremos agora programar o código para cada um de nossos botões.
Para isso faça a referência à DLL System.Data.SQLite.dll. Procure pelo arquivo que você descompactou, aquele que você fez o download.
Primeiro vamos criar a base de dados.
Para criar o arquivo de base de dados usamos o método estático System.Data.SQLite.SQLiteConnection.CreateFile.
Clique 2x no botão “Criar Base”. Segue o código do evento clique.
private void btnCriarBase_Click(object sender, EventArgs e) { try { string dbFile = "sqlLite.db"; //a extensão pode ser a que você quiser if (System.IO.File.Exists(dbFile)) System.IO.File.Delete(dbFile); System.Data.SQLite.SQLiteConnection.CreateFile(dbFile); MessageBox.Show(this, "Base de dados criada com sucesso.", "Aviso!", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(this, "Ocorreu um erro ao criar a base de dados.\n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
OK! Agora que criamos a base de dados precisamos criar as tabelas. O SQLite aceita os comando de criação de tabelas, CREATE TABLE, ALTER TABLE, DROP TABLE. Então vamos criar a nossa tabela.
Antes de criar as nossas tabelas precisamos conhecer as strings de conexões que podemos ter para o SQLite.
Se você não definiu nenhuma senha para sua base de dados, esta string é o suficiente.
Data Source=caminho completo do arquivo;Version=3;
Caso tenha definido uma senha, use esta string
Data Source=caminho completo do arquivo;Version=3;Password=senha;
Clique 2x no botão “Criar Tabelas”. Segue o código do evento clique.
private void btnCriarTabelas_Click(object sender, EventArgs e) { try { SQLiteConnection conn = OpenConnection(); //criamos um objeto Command; SQLiteCommand command = conn.CreateCommand(); //definimos o script de criação de tabelas string createTable = @"CREATE TABLE Pessoa ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Nome VARCHAR(100) NOT NULL, Telefone VARCHAR (30) )"; command.CommandText = createTable; command.ExecuteNonQuery(); //aqui iremos fazer um alter table apenas para mostrar que é possível string alterTable = "ALTER TABLE Pessoa ADD Column DataNascimento DATE"; command.CommandText = alterTable; command.ExecuteNonQuery(); MessageBox.Show(this, "Tabela criada com sucesso.", "Aviso!", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(this, "Ocorreu um erro ao criar a tabela na base de dados.\n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
Repare na linha em destaque o comando ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT aqui definimos que o campo ID será nossa chave primária do tipo inteiro e autoincremento. NO SQLite você não precisa definir a diretiva “AUTOINCREMENT“, pois por padrão toda chave primária do tipo inteiro é autoincremento. Mas, eu gosto de colocar.
Ok! Já criamos a nossa base de dados e já criamos a nossa tabela. Agora vamos manipular estes dados, para isso iremos codificar os botões btnInsert, btnUpdate, btnDelete e btnSelect.
Veja o código dos botões abaixo.
Botão btnInsert
private void btnInsert_Click(object sender, EventArgs e) { if (!Validate(false)) return; SQLiteConnection conn = OpenConnection(); SQLiteTransaction transaction = null; try { transaction = conn.BeginTransaction(); SQLiteCommand command = conn.CreateCommand(); string insertCommand = "INSERT INTO Pessoa (Nome, Telefone, DataNascimento) VALUES(?,?,?)"; command.Parameters.Add("Nome", DbType.String).Value = txtNome.Text; command.Parameters.Add("Telefone", DbType.String).Value = txtTelefone.Text; command.Parameters.Add("DataNascimento", DbType.Date).Value = dtDataNascimento.Text; command.CommandText = insertCommand; command.ExecuteNonQuery(); transaction.Commit(); btnSelect.PerformClick(); } catch (Exception ex) { if (transaction != null) transaction.Rollback(); MessageBox.Show(this, "Ocorreu um erro ao inserir os dados na tabela.\n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { conn.Close(); } }
Botão btnUpdate
private void Update_Click(object sender, EventArgs e) { if (!Validate(true)) return; SQLiteConnection conn = OpenConnection(); SQLiteTransaction transaction = null; try { transaction = conn.BeginTransaction(); SQLiteCommand command = conn.CreateCommand(); string updateCommand = "UPDATE Pessoa SET Nome = ?, Telefone = ?, DataNascimento =? WHERE ID = ?"; command.Parameters.Add("Nome", DbType.String).Value = txtNome.Text; command.Parameters.Add("Telefone", DbType.String).Value = txtTelefone.Text; command.Parameters.Add("DataNascimento", DbType.Date).Value = dtDataNascimento.Text; command.Parameters.Add("ID", DbType.Int32).Value = txtID.Text; command.CommandText = updateCommand; command.ExecuteNonQuery(); transaction.Commit(); btnSelect.PerformClick(); } catch (Exception ex) { if (transaction != null) transaction.Rollback(); MessageBox.Show(this, "Ocorreu um erro ao inserir os dados na tabela.\n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { conn.Close(); } }
Botão btnDelete
private void btnDelete_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtID.Text) || Convert.ToInt32(txtID.Text) == 0) { MessageBox.Show(this, "Selecione um registro para excluir!", "Exluir!", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SQLiteConnection conn = OpenConnection(); SQLiteTransaction transaction = null; try { transaction = conn.BeginTransaction(); SQLiteCommand command = conn.CreateCommand(); string deleteCommand = "DELETE FROM Pessoa WHERE ID = ?"; command.Parameters.Add("ID", DbType.Int32).Value = txtID.Text; command.CommandText = deleteCommand; command.ExecuteNonQuery(); transaction.Commit(); btnSelect.PerformClick(); } catch (Exception ex) { if (transaction != null) transaction.Rollback(); MessageBox.Show(this, "Ocorreu um erro ao excluir os dados da tabela.\n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { conn.Close(); } }
Botão btnSelect
private void btnSelect_Click(object sender, EventArgs e) { try { RefreshGrid(); } catch (Exception ex) { MessageBox.Show(this, "Ocorreu um erro ao selcionar os registros.\n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { } }
Precisaremos também de alguns métodos que irão nos auxiliar no decorrer do processo.
Preste atenção aos comentários de cada método.
#region Métodos Auxiliares /// /// abre uma conexão e retorna /// /// private SQLiteConnection OpenConnection() { string dbFile = "sqlLite.db"; //criamos a conexão com a base de dados SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbFile + ";Version=3;"); //abrimos a conexão conn.Open(); return conn; } /// /// atualiza a grid com os dados da base. /// private void RefreshGrid() { SQLiteConnection conn = OpenConnection(); SQLiteCommand command = conn.CreateCommand(); command.CommandText = "SELECT ID, Nome, Telefone, DataNascimento AS 'Data Nascto' FROM Pessoa"; SQLiteDataReader rs = command.ExecuteReader(); BindDataGrid(dataGridView, rs); conn.Close(); } /// /// cria os campos da grid e prepara para exibir os dados da base /// /// <param name="_dataGrid" />datagridview que deverá ser preparada /// <param name="_rs" />recordset com os dados que deverão ser populados na grid private void BindDataGrid(DataGridView _dataGrid, SQLiteDataReader _rs) { _dataGrid.Rows.Clear(); _dataGrid.Columns.Clear(); for (int i = 0; i < _rs.FieldCount; i++) { DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn(); col.HeaderText = _rs.GetName(i); col.Visible = true; col.Name = "col" + i; col.Resizable = DataGridViewTriState.True; _dataGrid.Columns.Add(col); } while (_rs.Read()) { object[] row = new object[_rs.FieldCount]; for (int i = 0; i < _rs.FieldCount; i++) { row[i] = FormatValue(_rs.GetValue(i), _rs.GetDataTypeName(i)); } _dataGrid.Rows.Add(row); } } /// /// Formata um valor para ser exibido na grid /// /// <param name="fieldValue" />valor do campo /// <param name="fieldType" />tipo do campo /// private object FormatValue(object fieldValue, string fieldType) { string ret = ""; if (fieldType.ToUpper() == "DATE")//só nos interessa o campo data para exemplo ret = string.Format("{0:dd/MM/yyyy}", fieldValue); else ret = fieldValue.ToString(); return ret; } /// /// valida os dados do formulário e retorna /// /// <param name="update" />se true valida o ID /// new private bool Validate(bool update) { if (string.IsNullOrEmpty(txtNome.Text)) { MessageBox.Show(this, "Nome é obrigatório!", "Campo Obrigatório!", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } if (string.IsNullOrEmpty(txtTelefone.Text)) { MessageBox.Show(this, "Telefone é obrigatório!", "Campo Obrigatório!", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } if (update) { if (string.IsNullOrEmpty(txtID.Text) || Convert.ToInt32(txtID.Text) == 0) { MessageBox.Show(this, "Selecione um registro para continuar!", "Registro!", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } } return true; } #endregion
Com isso apresentei a vocês o SQLite, com este tutorial você aprendeu tudo que é preciso para fazer uma aplicação usando esta base de dados embarcada.
Para saber mais sobre o SQLite Provider acesse o link http://system.data.sqlite.org
Para saber mais sobre o SQLite acesse o link http://sqlite.org/docs.html
Para saber mais sobre as strings de conexão para SQLite acesse o link http://www.connectionstrings.com/sqlite
Se tiver alguma dúvida, utilize o nosso fórum de C# link https://techblog.desenvolvedores.net/bbpress/forum.php?id=2
Download para o projeto de exemplo [download id=”15″]
É isso ai pessoal 🙂
Até o próximo
♦ Marcelo