import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 使用datasource方法建立mysql数据库连接。
* @author bestree007;
*
*/
public class MYSQLConnection {
public static void main(String[] args) {
com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
Connection conn2;
// create connection with a datasource object
ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
ds.setServerName("localhost");
ds.setDatabaseName("bestree");
ds.setPort(3306);
// ds.setURL("jdbc:mysql://localhost:3306/bestree");
try {
conn2 = ds.getConnection("bestree", "password");
if (!conn2.isClosed()) {
System.out.println("Succeeded connecting to the Database!");
}
Statement statement = conn2.createStatement();
String sql = "select * from pet";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
rs.close();
conn2.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用datasource的方法建立到MySQL数据的连接。
最新推荐文章于 2024-08-19 21:34:18 发布