/**
Manifest-Version: 1.0
Created-By: 1.4.2-b28 (Sun Microsystems Inc.)
Specification-Title: FirebirdSQL JayBird
Specification-Version: 1.5
Specification-Vendor: FirebirdSQL (http://www.firebirdsql.org)
Implementation-Title: JayBird
Implementation-URL: http://www.firebirdsql.org
Implementation-Version: 1.5.5JDK_1.4 (build: CVSTag=HEAD date=20041205
1247)
Implementation-Vendor: FirebirdSQL
Implementation-Vendor-Id: http://www.firebirdsql.org
Подключение БД на Interbase к программе на Java
Возникла серьезная проблема. Не могу узнать название драйвера JDBC для Interbase 7.01. Подскажите его название, где взять и как с ним работать, потому что в руководствах в Инете в основном приводятся "типичные примеры подключения", очень поверхностные и с кучей ошибок, а мне нужно как можно подробнее. Заранее благодарен.
вот файл-манифест
Код:
Пример подключения.
Код:
JDBCAdapter ja2;
///dbURL= "jdbc:firebirdsql:localhost:c:/windows/system32/railway.fdb";
dbURL= "jdbc:firebirdsql:localhost:railway.fdb";
user = "sysdba";
passwd = "masterkey";
driver = "org.firebirdsql.jdbc.FBDriver";
ja2 = new JDBCAdapter(dbURL, driver, user, passwd);
///dbURL= "jdbc:firebirdsql:localhost:c:/windows/system32/railway.fdb";
dbURL= "jdbc:firebirdsql:localhost:railway.fdb";
user = "sysdba";
passwd = "masterkey";
driver = "org.firebirdsql.jdbc.FBDriver";
ja2 = new JDBCAdapter(dbURL, driver, user, passwd);
Класс JDBCAdapter можно посмотреть в папке Demos(и еще чего много там есть)
C:\Program Files\Java\jdk1.5.0_05\demo\jfc\TableExample\src
Только там табличную модель(грубо говоря матрица-таблица-результат запроса) и взаимодействие с субд вместе слепили, что плохо
Я разнес на два класса, может сильно обрезал, но для меня сойдет, держи эти классы
Код:
//JDBCAdapter.java
import java.util.Vector;
import java.sql.*;
public class JDBCAdapter {
Connection connection;
Statement statement;
ResultSet resultSet;
String[] columnNames = {};
Vector rows = new Vector();
ResultSetMetaData metaData;
boolean AutoCommit=false;
public void rollback(){
try { if (connection!=null) connection.rollback(); } catch (java.sql.SQLException e) { System.out.println(e); }
}
public void commit(){
try { if (connection!=null) connection.commit(); } catch (java.sql.SQLException e) { System.out.println(e); }
}
public Vector getRows()
{
return rows;
}
public String[] getColumnNames()
{
return columnNames;
}
public JDBCAdapter(String url, String driverName,
String user, String passwd) {
try {
Class.forName(driverName);
System.out.println("Opening db connection");
connection = DriverManager.getConnection(url, user, passwd);
connection.setAutoCommit(AutoCommit);
statement = connection.createStatement();
}
catch (ClassNotFoundException ex) {
System.err.println("Cannot find the database driver classes.");
System.err.println(ex);
}
catch (SQLException ex) {
System.err.println("Cannot connect to this database.");
System.err.println(ex);
}
}
public void executeQuery(String query){
/// System.out.println(query);
if (connection == null || statement == null) {
System.err.println("There is no database to execute the query.");
return;
}
try {
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
// Get the column names and cache them.
// Then we can close the connection.
for(int column = 0; column < numberOfColumns; column++) {
columnNames[column] = metaData.getColumnLabel(column+1);
}
// Get all rows.
rows = new Vector();
while (resultSet.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= getColumnCount(); i++) {
newRow.addElement(resultSet.getObject(i));
}
rows.addElement(newRow);
}
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
//reTableChanged(null); // Tell the listeners a new table has arrived.
}
catch (SQLException ex) {
System.err.println(ex);
}
}
public int getColumnCount() {
return columnNames.length;
}
public void close() throws SQLException {
System.out.println("Closing db connection");
rollback();
if(resultSet != null)
resultSet.close();
statement.close();
connection.close();
}
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
import java.util.Vector;
import java.sql.*;
public class JDBCAdapter {
Connection connection;
Statement statement;
ResultSet resultSet;
String[] columnNames = {};
Vector rows = new Vector();
ResultSetMetaData metaData;
boolean AutoCommit=false;
public void rollback(){
try { if (connection!=null) connection.rollback(); } catch (java.sql.SQLException e) { System.out.println(e); }
}
public void commit(){
try { if (connection!=null) connection.commit(); } catch (java.sql.SQLException e) { System.out.println(e); }
}
public Vector getRows()
{
return rows;
}
public String[] getColumnNames()
{
return columnNames;
}
public JDBCAdapter(String url, String driverName,
String user, String passwd) {
try {
Class.forName(driverName);
System.out.println("Opening db connection");
connection = DriverManager.getConnection(url, user, passwd);
connection.setAutoCommit(AutoCommit);
statement = connection.createStatement();
}
catch (ClassNotFoundException ex) {
System.err.println("Cannot find the database driver classes.");
System.err.println(ex);
}
catch (SQLException ex) {
System.err.println("Cannot connect to this database.");
System.err.println(ex);
}
}
public void executeQuery(String query){
/// System.out.println(query);
if (connection == null || statement == null) {
System.err.println("There is no database to execute the query.");
return;
}
try {
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
// Get the column names and cache them.
// Then we can close the connection.
for(int column = 0; column < numberOfColumns; column++) {
columnNames[column] = metaData.getColumnLabel(column+1);
}
// Get all rows.
rows = new Vector();
while (resultSet.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= getColumnCount(); i++) {
newRow.addElement(resultSet.getObject(i));
}
rows.addElement(newRow);
}
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
//reTableChanged(null); // Tell the listeners a new table has arrived.
}
catch (SQLException ex) {
System.err.println(ex);
}
}
public int getColumnCount() {
return columnNames.length;
}
public void close() throws SQLException {
System.out.println("Closing db connection");
rollback();
if(resultSet != null)
resultSet.close();
statement.close();
connection.close();
}
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
Код:
//JDBCTableModel.java
//import java.sql.*;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;
public class JDBCTableModel extends AbstractTableModel {
String[] columnNames = {};
Vector rows;
public void setData(Vector V,String[] ColumnNames) {
rows = V;
columnNames = ColumnNames;
fireTableChanged(null);
}
//////////////////////////////////////////////////////////////////////////
//
// Implementation of the TableModel Interface
//
//////////////////////////////////////////////////////////////////////////
// MetaData
public String getColumnName(int column) {
if (columnNames[column] != null) {
return columnNames[column];
} else {
return "";
}
}
/* public Class getColumnClass(int column) {
int type;
try {
type = metaData.getColumnType(column+1);
}
catch (SQLException e) {
return super.getColumnClass(column);
}
switch(type) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String.class;
case Types.BIT:
return Boolean.class;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return Integer.class;
case Types.BIGINT:
return Long.class;
case Types.FLOAT:
case Types.DOUBLE:
return Double.class;
case Types.DATE:
return java.sql.Date.class;
default:
return Object.class;
}
}
*/
/* public boolean isCellEditable(int row, int column) {
try {
return metaData.isWritable(column+1);
}
catch (SQLException e) {
return false;
}
}*/
public int getColumnCount() {
return columnNames.length;
}
// Data methods
public int getRowCount() {
return rows.size();
}
public Object getValueAt(int aRow, int aColumn) {
Vector row = (Vector)rows.elementAt(aRow);
return row.elementAt(aColumn);
}
/*
public String dbRepresentation(int column, Object value) {
int type;
if (value == null) {
return "null";
}
try {
type = metaData.getColumnType(column+1);
}
catch (SQLException e) {
return value.toString();
}
switch(type) {
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
return value.toString();
case Types.BIT:
return ((Boolean)value).booleanValue() ? "1" : "0";
case Types.DATE:
return value.toString(); // This will need some conversion.
default:
return "\""+value.toString()+"\"";
}
}*/
//public void setValueAt(Object value, int row, int column) { }
}
//import java.sql.*;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;
public class JDBCTableModel extends AbstractTableModel {
String[] columnNames = {};
Vector rows;
public void setData(Vector V,String[] ColumnNames) {
rows = V;
columnNames = ColumnNames;
fireTableChanged(null);
}
//////////////////////////////////////////////////////////////////////////
//
// Implementation of the TableModel Interface
//
//////////////////////////////////////////////////////////////////////////
// MetaData
public String getColumnName(int column) {
if (columnNames[column] != null) {
return columnNames[column];
} else {
return "";
}
}
/* public Class getColumnClass(int column) {
int type;
try {
type = metaData.getColumnType(column+1);
}
catch (SQLException e) {
return super.getColumnClass(column);
}
switch(type) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String.class;
case Types.BIT:
return Boolean.class;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return Integer.class;
case Types.BIGINT:
return Long.class;
case Types.FLOAT:
case Types.DOUBLE:
return Double.class;
case Types.DATE:
return java.sql.Date.class;
default:
return Object.class;
}
}
*/
/* public boolean isCellEditable(int row, int column) {
try {
return metaData.isWritable(column+1);
}
catch (SQLException e) {
return false;
}
}*/
public int getColumnCount() {
return columnNames.length;
}
// Data methods
public int getRowCount() {
return rows.size();
}
public Object getValueAt(int aRow, int aColumn) {
Vector row = (Vector)rows.elementAt(aRow);
return row.elementAt(aColumn);
}
/*
public String dbRepresentation(int column, Object value) {
int type;
if (value == null) {
return "null";
}
try {
type = metaData.getColumnType(column+1);
}
catch (SQLException e) {
return value.toString();
}
switch(type) {
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
return value.toString();
case Types.BIT:
return ((Boolean)value).booleanValue() ? "1" : "0";
case Types.DATE:
return value.toString(); // This will need some conversion.
default:
return "\""+value.toString()+"\"";
}
}*/
//public void setValueAt(Object value, int row, int column) { }
}
пример использования
Код:
JDBCTableModel dtmObj;
JScrollPane jsPane;
JTable tableCVR;
Container contentPane = getContentPane();
dtmObj = new JDBCTableModel();
ja2.executeQuery("Select num \"Число\" from table_num where num > 0");
dtmObj.setData(ja2.getRows(),ja2.getColumnNames());
tableCVR = new JTable(dtmObj);
jsPane = new JScrollPane(tableCVR);
contentPane.add(jsPane,"Center");
//dtmObj.getValueAt(0,0);
JScrollPane jsPane;
JTable tableCVR;
Container contentPane = getContentPane();
dtmObj = new JDBCTableModel();
ja2.executeQuery("Select num \"Число\" from table_num where num > 0");
dtmObj.setData(ja2.getRows(),ja2.getColumnNames());
tableCVR = new JTable(dtmObj);
jsPane = new JScrollPane(tableCVR);
contentPane.add(jsPane,"Center");
//dtmObj.getValueAt(0,0);
этот jar-архив должен находиться в папке с прогой, где компилишь и выполняешь, а вот как это делается.
javac -classpath .;firebirdsql-full.jar %1.java
java -classpath .;firebirdsql-full.jar %1