答案 0 :(得分:2)
首先需要加载derby驱动程序类。为此,请在DriverManager.getConnection()
调用之前添加此代码。
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");// or may be it is "org.apache.derby.jdbc.EmbeddedDriver"? Not sure. Check the correct name and put it here.
} catch(ClassNotFoundException e){
//handle exception
}
这将在JDBC驱动程序注册表中加载并注册Derby驱动程序类,之后您将能够连接到数据库。
有关详细信息,请参阅此处:
https://db.apache.org/derby/docs/10.4/devguide/cdevdvlp40653.html
更新
derby安装的lib文件夹中应该有一个derbyclient.jar
。您还需要将其添加到类路径并在运行时使其可用。这似乎解决了我的问题。
希望这有帮助!
答案 1 :(得分:0)
It simole example for you:
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
//You must use driver, but you can use this driver:
// static String DB_URL = "com.mysql.cj.jdbc.Driver";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}
Также хороший совет- читай и пиши на английском, IDE также свою переведи на английский (а вообще советую Intellij idea, у которой, кстати есть бесплатные лицензии для школьников и студентов.).
NetBeans的Вотссылканастатьюосменеязыка http://blog.matros.com.ua/%D0%BA%D0%B0%D0%BA-%D0%B8%D0%B7%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C-%D1%8F%D0%B7%D1%8B%D0%BA-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D1%84%D0%B5%D0%B9%D1%81%D0%B0-%D0%B2-netbeans-7-3-%D0%BD%D0%B0-%D0%B0%D0%BD/