【java】mysql的简单查询

/**
 * 使用idea连接数据库,简单实现查询数据库的数据
 * 
 * 依赖org.wisdom-framework:mysql-connector-java:5.1.34_1
 * 
 * */
public class MySqlTest {

    private static String url="jdbc:mysql://localhost:3306/MySqlTest";

    private static String username="root";

    private static String password="123456";

    private static String driver="com.mysql.jdbc.Driver";


    public static void main(String[] args) {
        init();
    }

    public static void init(){

        try{
            //加载驱动
            Class.forName(driver);

            Connection conn= DriverManager.getConnection(url,username,password);
            Statement sql_statement=conn.createStatement();

            if(!conn.isClosed()){

                System.out.println("连接数据库成功");

                //查询语句
                String query="select * from table_name";
                ResultSet result=sql_statement.executeQuery(query);

                while (result.next()){
                    String name=result.getString("name");
                    System.out.println("获得结果"+name);
                }



            }else {
                System.out.println("连接数据库失败");
            }

            sql_statement.close();
            conn.close();


        }catch (SQLException e){
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(java,mysql)