JDBC(最简单方法)

    技术2024-12-20  41

    java连接mysql数据库 1.加载驱动

    Class.forName("com.mysql.jdbc.Driver");

    2.获取连接对象

    Connection conn =DriverManager.getConnection ("jdbc:mysql://localhost:3306/3-15","root","root");

    3.获取Statement

    Statement st=conn.createStatement();

    4.查询

    ResultSet re = st.executeQuery("select * from course");

    5.遍历

    while(re.next()) { System.out.println (re.getString(1)+re.getString(2)+re.getString(3)); }

    6.按出栈顺序关闭

    re.close(); st.close(); conn.close();

    完整代码:

    package com.xxx.web; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConnectMysql { public static void main(String[] args) throws ClassNotFoundException, SQLException { // 加载驱动 Class.forName("com.mysql.jdbc.Driver"); //获取连接对象 Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/3-15","root","root"); //获取Statement Statement st=conn.createStatement(); //查询 ResultSet re = st.executeQuery("select * from course"); //遍历 while(re.next()) { System.out.println(re.getString(1)+re.getString(2)+re.getString(3)); } re.close(); st.close(); conn.close(); } }
    Processed: 0.021, SQL: 9