首先获取JDBC驱动程序,比如mysql的connector/j-将jar添加到项目中。然后,您可以访问数据库,如:
公共类mysqltest{
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String protocol = "jdbc:mysql://localhost/";
String database = "database";
String username = "mysqlUsername";
String password = "mysqlPassword";
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
Connection conn;
Statement s;
ResultSet rs;
String createTableStatment = "CREATE TABLE test ( `id` INTEGER NOT NULL)";
String insertStatment = "INSERT INTO test VALUES(1)";
String selectQuery = "SELECT * FROM test";
try {
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(protocol + database,props);
conn.setAutoCommit(true);
s = conn.createStatement();
s.execute(createTableStatment);
s.execute(insertStatment);
rs = s.executeQuery(selectQuery);
while (rs.next()){
System.out.println("id = "+rs.getString("id"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}