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(); } } } }
相关推荐
gaozhennan 2020-08-03
大黑牛 2020-08-15
ASoc 2020-11-14
Cherishyuu 2020-08-19
dongtiandeyu 2020-08-18
CoderYYN 2020-08-16
Dullonjiang 2020-08-11
mcvsyy 2020-08-02
zbcaicai 2020-07-29
AscaryBird 2020-07-27
liulin0 2020-07-26
ldcwang 2020-07-26
helloxusir 2020-07-25
娜娜 2020-07-20
pengpengflyjhp 2020-07-19
点滴技术生活 2020-07-19
人可 2020-07-18
chenjiazhu 2020-07-08
langyue 2020-07-06