JDBC连接MySQL

依赖

<!-- mysql连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

代码实现

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @description: TODO
 * @author: HaoWu
 * @create: 2020年09月18日
 */
public class JDBCTest {
    public static void main(String[] args) throws Exception {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取与数据库的链接
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "root";
        Connection conn = null;
        conn = DriverManager.getConnection(url, username, password);
        //3.获取用于向数据库发送sql语句的Preperedstatement
        PreparedStatement st = null;
        String sql = "select * from users where name=? and password=?";
        st = conn.prepareStatement(sql);//在此次传入,进行预编译
        st.setString(1, username);
        st.setString(2, password);

        //4.向数据库发sql,并获取代表结果集的resultset
        ResultSet rs = null;
        rs = st.executeQuery(sql);

        //5.取出结果集的数据
        //循环取出(id)
        while (rs.next()) {
            String id = rs.getString(1);//1代表数据库中表的列数,id在第一列也可以("id")!!!
            System.out.println(id + " ");
        }
        //6.关闭链接,释放资源
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;

        }
        if (st != null) {
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

相关推荐