用JAVA程序操作MYSQL数据库
下载MySQL连接驱动:mysql-connector-java-5.1.46.jar
加载驱动:
1. 在工程目录中创建lib文件夹,将下载好的JDBC放到该文件夹下,如下图所示:
2.右键工程名,点击build path的Configure Build Path中,进入java build path中的Libraries分页中选择Add JARs…,选择刚才添加的JDBC,如下图:
连接数据库并读取数据:
代码为:
package sqldemo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class main {
public static void main(String[] args) {
Connection con; //声明Connection对象
String driver = "com.mysql.jdbc.Driver"; //驱动程序名
String url = "jdbc:mysql://localhost:3306/person";//URL指向要访问的数据库名mydata
String user = "root";//MySQL配置时的用户名
String password = ""; //MySQL配置时的密码
//遍历查询结果集
try {
Class.forName(driver); //加载驱动程序
//1.getConnection()方法,连接MySQL数据库!!
con = (Connection) DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
Statement statement = (Statement) con.createStatement(); //2.创建statement类对象,用来执行SQL语句!!
String sql = "select * from info";//要执行的SQL语句
ResultSet rs = statement.executeQuery(sql); //3.ResultSet类,用来存放获取的结果集!!
System.out.println("------------------------");
System.out.println("执行结果如下所示:");
System.out.println("---------------------------");
System.out.println("id"+"\t"+"姓名" + "\t" + "性别"+"\t" +"年龄");
System.out.println("---------------------------");
while(rs.next()){
System.out.println( rs.getInt("id") +"\t" +rs.getString("name") + "\t" + rs.getString("sex") + "\t" +rs.getInt("age") + "\t");
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!");
}
}
}
运行的效果图为: