Boa tarde, estou aprendendo a utilizar o banco hsqldb mas não estou conseguindo salvar valores de variáveis na tabela, consigo salvar apenas valor diretos.
DUVIDA NA LINHA 173
Abaixo o código:
package project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
* Title: Testdb
* Description: simple hello world db example of a
* standalone persistent db application
*
* every time it runs it adds four more rows to sample_table
* it does a query and prints the results to standard out
*
* Author: Karl Meissner [email removido]
*/
public class MainProject {
private static Scanner leitor = new Scanner(System.in);
Connection conn; //our connnection to the db - presist for life of program
private String opcao;
// we dont want this garbage collected until we are done
public MainProject(String db_file_name_prefix) throws Exception { // note more general exception
// Load the HSQL Database Engine JDBC driver
// hsqldb.jar should be in the class path or made part of the current jar
Class.forName("org.hsqldb.jdbcDriver");
// connect to the database. This will load the db files and start the
// database if it is not alread running.
// db_file_name_prefix is used to open or create files that hold the state
// of the db.
// It can contain directory names relative to the
// current working directory
conn = DriverManager.getConnection("jdbc:hsqldb:"
+ db_file_name_prefix, // filenames
"sa", // username
""); // password
}
public void shutdown() throws SQLException {
Statement st = conn.createStatement();
// db writes out to files and performs clean shuts down
// otherwise there will be an unclean shutdown
// when program ends
st.execute("SHUTDOWN");
conn.close(); // if there are no other open connection
}
//use for SQL command SELECT
public synchronized void query(String expression) throws SQLException {
Statement st = null;
ResultSet rs = null;
st = conn.createStatement(); // statement objects can be reused with
// repeated calls to execute but we
// choose to make a new one each time
rs = st.executeQuery(expression); // run the query
// do something with the result set.
dump(rs);
st.close(); // NOTE!! if you close a statement the associated ResultSet is
// closed too
// so you should copy the contents to some other object.
// the result set is invalidated also if you recycle an Statement
// and try to execute some other query before the result set has been
// completely examined.
}
//use for SQL commands CREATE, DROP, INSERT and UPDATE
public synchronized void update(String expression) throws SQLException {
Statement st = null;
st = conn.createStatement(); // statements
int i = st.executeUpdate(expression); // run the query
if (i == -1) {
System.out.println("db error : " + expression);
}
st.close();
} // void update()
public static void dump(ResultSet rs) throws SQLException {
// the order of the rows in a cursor
// are implementation dependent unless you use the SQL ORDER statement
ResultSetMetaData meta = rs.getMetaData();
int colmax = meta.getColumnCount();
int i;
Object o = null;
// the result set is a cursor into the data. You can only
// point to one row at a time
// assume we are pointing to BEFORE the first row
// rs.next() points to next row and returns true
// or false if there is no next row, which breaks the loop
for (; rs.next(); ) {
for (i = 0; i < colmax; ++i) {
o = rs.getObject(i + 1); // Is SQL the first column is indexed
// with 1 not 0
System.out.print(o.toString() + " ");
}
System.out.println(" ");
}
} // void dump( ResultSet rs )
public static void main(String[] args) {
String opcao;
MainProject db = null;
try {
db = new MainProject("db_file.db");
} catch (Exception ex1) {
ex1.printStackTrace(); // could not start db
return; // bye bye
}
try {
//make an empty table
//
// by declaring the id column IDENTITY, the db will automatically
// generate unique values for new rows- useful for row keys
db.update(
"CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)");
} catch (SQLException ex2) {
//ignore
//ex2.printStackTrace(); // second time we run program
// should throw execption since table
// already there
//
// this will have no effect on the db
}
try {
do{
System.out.println("\n1. Cadastrar Carro e Kilometragem:");
System.out.println("2. Listar os carros cadastrados:");
System.out.println("3. Sair");
System.out.println("\nEscolha a opçao desejada:");
opcao = leitor.nextLine();
if(opcao.equals("1")){
//cadastrar um carro e a kilometragem total do carro
String nome;
String quilometragem;
System.out.println("Qual o nome do carro?");
nome = leitor.nextLine();
System.out.println("Qual o Quilometragem do carro?");
quilometragem = leitor.nextLine();
//*********** DUVIDA NO INSERT *******************
// Quero salvar no banco o conteúdo das variáveis
db.update(
"INSERT INTO sample_table(str_col,num_col) VALUES('nome', 100)");
// nome, quilometragem
//************************************************
}else if(opcao.equals("2")){
// listar o conteúdo da tabela
System.out.println("Dados inseridos com sucesso!\n\n");
// do a query
System.out.println("DADOS CONTIDOS NA TABELA:\n");
db.query("SELECT * FROM sample_table");
}else if(opcao.equals("3")){
// SAIR DO PROGRAMA
db.shutdown();
}else{
System.out.println("\nOpção Invalida!!!");
}
} while (!opcao.equals("3"));
} catch (SQLException ex3) {
ex3.printStackTrace();
}
} // fim da main()
} // fim da classe Testdb
Obrigado,
Sandro