java连接mysql

2016-11-05  邓智群 

java连接mysql步骤如下:

1、加载驱动

2、建立连接

3、创建statement对象

4、创建数据结果对象

5、遍历输出

6、关闭


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;




public class Mysql {
public static void main(String[]args){
//加载驱动器
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
//建立连接
String url = "jdbc:mysql://localhost:3306/test";
Connection coon;
try{
coon = DriverManager.getConnection(url,"root","tongji");
Statement stmt = coon.createStatement();
String sql = "select * from student";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getInt(1)+"\t");
}
//依次关闭
rs.close();
stmt.close();
coon.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}

384°/3841 人阅读/0 条评论 发表评论

登录 后发表评论