加载和连接

来源:互联网 发布:问道辅助软件 编辑:程序博客网 时间:2024/05/16 05:58
package com.sql.zmz;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Connection;import java.sql.Statement;import javax.sql.RowSet;  public class Test1{    static Statement sql;        static Connection con;        static ResultSet res;        public Connection getConection() {        try {Class.forName("com.mysql.jdbc.Driver");System.out.println("数据库驱动加载成功");} catch (ClassNotFoundException e) {e.printStackTrace();}        String url = "jdbc:mysql://localhost:3306/test_db?user=root&password=123456&useSSL=true";        try {        con = DriverManager.getConnection(url);System.out.println("连接数据库成功");} catch (SQLException  e) {// TODO: handle exceptione.printStackTrace();}        return con;        }                public static void main(String[] args) {Test1 c = new Test1();con = c.getConection();try {sql = con.createStatement();res = sql.executeQuery("select*from tb_emp1");//res = sql.executeQuery("select*from tb_emp1 where name like '张%' ");while(res.next()) {String id = res.getString("id");String name = res.getString("name");String deptId = res.getString("deptId");String salary = res.getString("salary");System.out.print("编号:"+id);System.out.print("姓名:"+name);System.out.print("工号:"+deptId);System.out.print("薪水"+salary);System.out.println("");}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}     }