JDBC连接实例

 1 package com.javaee.corejava;

 2 

 3 import java.sql.Connection;

 4 import java.sql.DriverManager;

 5 import java.sql.PreparedStatement;

 6 import java.sql.ResultSet;

 7 

 8 public class JDBCConnect {

 9 

10     public JDBCConnect() {

11         // TODO Auto-generated constructor stub

12     }

13 

14     public static void main(String[] args) {

15         try {

16             //加载mysql的JDBC驱动

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

18             String url="jdbc://localhost:3306/v3x";

19             String userName="root";

20             String pwd="123456";

21             //获取数据库连接

22             Connection con= DriverManager.getConnection(url, userName, pwd);

23             String sql="select * from ctp_affair where id=?";

24             //Statement stmt=con.createStatement();

25             PreparedStatement pstmt=con.prepareStatement(sql);

26             pstmt.setLong(1, 0L);

27             //执行查询

28             ResultSet rs=pstmt.executeQuery();

29             while(rs.next()){

30                 String subject=rs.getString("subject");

31             }

32             //关闭连接,释放资源

33             rs.close();// 关闭记录集   

34             pstmt.close();// 关闭声明   

35             con.close();// 关闭连接对象   

36         } catch (Exception e) {

37             e.printStackTrace();

38         }

39         

40 

41     }

42 

43 }

 

你可能感兴趣的:(jdbc)