JAVA-1.连接数据库

 1 import java.sql.*;
 2 import com.mysql.jdbc.Driver;
 3 /*
 4  * 《JDBC基础篇》
 5  * 连接数据库一般来说分为6个步骤:
 6  *1-加载驱动
 7  *2-建立连接
 8  *3-创建语句
 9  *4-执行语句
10  *5-处理结果
11  *6-关闭资源
12  *
13  */
14 public class Jdbc {
15         //JDBC = Java Database Connection (用Java程序连接数据库并操作)
16     public static void main(String[] args) throws ClassNotFoundException, SQLException {
17         // TODO Auto-generated method stub
18         //1-加载驱动 合并写法:
19         Class.forName("com.mysql.jdbc.Driver");
20         //2-建立连接
21         //URL路径结构:
22         //协议://主机名或IP:端口/下层路径
23 
24         Connection conn = DriverManager.getConnection
25                 ("jdbc:mysql://localhost:3306/test","root","******");
26         
27         System.out.println(conn);
28         //3-创建语句
29         Statement st=conn.createStatement();
30         //4-执行语句
31         ResultSet rs=st.executeQuery("select * from qq");
32         //5-处理结果
33         rs.beforeFirst();//定位到首行之前
34         while(rs.next()) {//判断下一行是否有数据,并循环
35             //用字段编号获取
36             String name =rs.getString(1);
37             int age=rs.getInt(2);
38             double height=rs.getDouble(3);
39             System.out.println(name+"\t"+age+"\t"+height);
40         }
41         //6-关闭资源
42         rs.close();
43         st.close();
44         conn.close();
45         
46 /*        Java反射机制:Java语言是面向对象的,可以把Java代码自身当做对象处理
47 
48         数据库的表对应于Java类(实体),表的字段(列)对应于类的字段(属性)
49         所以,可以把对数据库表的操作,对应为对类和对象的操作
50 
51         DAO = Data Access Object (数据访问对象)
52 */
53     }
54 
55 }

猜你喜欢

转载自www.cnblogs.com/xiaoluohao/p/9191915.html