Java连接Mysql 数据库主要分为四个步骤:
- 加载数据库驱动。通常使用Class类的forName()静态方法来加载驱动
Class.forName("com.mysql.jdbc.Driver");
- 通过DriverManager 获取数据库连接
Connection conn = DriverManager.getConnection(String url,String user,String pass);
mysql的URL写法为:
jdbc:mysql://hostname:port/databasement
-通过Connection 创建Statement 对象
Statement stmt = conn.createStatement();
- 使用Statement执行SQL语句
ResultSet rs = stmt.executeQuery(SQL)
完整代码为
package com.learning;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/crm"
,"root","root");
Statement stmt = conn.createStatement();
String sql = "select * from sys_user" ;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println( rs.getString(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getString(3));
}
}
}
网友评论