import java.sql.DriverManager
import java.sql.SQLExceptionpublic class DBUtil { static String jdbcURL = "jdbc:mysql://localhost:3306/book"
static String jdbcDriver = "com.mysql.jdbc.Driver"
static String userName = "root"
static String password = "root"
/**
* @return 数据库连接对象
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
Class.forName(jdbcDriver)
return DriverManager.getConnection(jdbcURL, userName, password)
}
} 2。项目名==>右键==>build path==>add external archivers.... 选择你mysql驱动 添加进去就ok了
用JDBC连接数据库,然后用sql语句。要导入mysql的驱动包。import java.sql.*
public class TestMySql {
static Connection con = null// 声明Connection对象
static Statement sql = null
static ResultSet res = null
public static void main(String[] args) {
TestMySql c = new TestMySql()
con = c.getConnection()
try {
sql = con.createStatement()
res = sql.executeQuery("select * from dept")
//sql语句,我数据库里有张dept表
while (res.next()) {//输出结果
System.out.print(res.getString(1) + "<——>")
System.out.print(res.getString(2) + "<——>")
System.out.print(res.getString(3) )
System.out.println()
}
} catch (SQLException e) {
e.printStackTrace()
} finally {
try {
if (res != null) {
res.close()
res =null
}
if (sql != null) {
sql.close()
sql =null
}
if (con != null) {
con.close()
con =null
}
} catch (SQLException e) {
e.printStackTrace()
}
}
}
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver")
// 加载oracleJDBC驱动
System.out.println("数据库驱动加载成功")
} catch (ClassNotFoundException e) {
e.printStackTrace()
}
try {// 通过访问数据库的URL获取数据库连接对象
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydata", "root", "qwer1234")
//mydata为mysql名字
System.out.println("数据库连接成功")
} catch (SQLException e) {
e.printStackTrace()
}
return con// 按方法要求返回一个Connection对象
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)