方法步骤:1,将mysql链接接上

              2,TSQL和Student类在kingkit包中

              3,新建数据库data1

              4,在数据库data1下创建student表,插入几组数据,数据属性分别为 varchar,int,int

            

1 package kingkit;
2
3  import java.awt.List;
4  import java.sql.DriverManager;
5  import java.sql.SQLException;
6  import java.util.ArrayList;
7  import com.mysql.jdbc.Connection;
8  import com.mysql.jdbc.PreparedStatement;
9 import com.mysql.jdbc.ResultSet;
10 import com.mysql.jdbc.Statement;
11
12 public class TSQL {
13
14
15
16 public TSQL( ){
17
18 }
19
20 public static void main(String[] args) throws SQLException {
21
22 //注册驱动
23 try {
24 Class.forName("com.mysql.jdbc.Driver");
25 String url = "jdbc:mysql://localhost:3306/data1";
26 String user="root";
27 String password="";
28 /*
29 创建连接
30 */
31 Connection cnn =(Connection) DriverManager.getConnection(url, user, password);
32 /*
33 创建对象执行
34 */
35
36 Student stu= new Student("quexiaoxia",33,18);
37 /*
38 讲学生对象的属性加进数据库中
39 stmt为执行对象
40 */
41
42 ArrayList<Student> list=new ArrayList<Student>( );
43 PreparedStatement stmt=(PreparedStatement) cnn.prepareStatement("insert into student values(?,?,?)");
44 stmt.setString(1, stu.getName());
45 stmt.setInt(2,stu.getId());
46 stmt.setInt(3,stu.getAge());
47 stmt.execute();
48
49 /*
50 从数据库中取得数据放进学生对象中
51 学生对象放进ArrayList表中
52 */
53
54 ResultSet rss=(ResultSet) stmt.executeQuery("select name,id,age from student ");
55 while(rss.next()){
56
57 Student st=new Student( );
58 st.setName(rss.getString(1));
59 st.setId(rss.getInt(2));
60 st.setAge(rss.getInt(3));
61 list.add(st);
62
63 }
64 /*
65 控制台
66 输出数据库信息
67 */
68 for(Student s:list){
69
70 System.out.println(s.getName()+" "+s.getId()+" "+s.getAge());
71
72 }
73
74
75
76 /*
77 关闭数据库操作
78 */
79 stmt.close();
80 cnn.close();
81
82
83 } catch (ClassNotFoundException e) {
84 // TODO Auto-generated catch block
85 e.printStackTrace();
86 }
87 }
88
89 }
90

 

 

 

1 package kingkit;
2
3 public class Student {
4
5 private String name;
6 private int id;
7 private int age;
8
9 public Student( ){
10
11 }
12
13 public Student( String name,int id,int age){
14
15 this.name=name;
16 this.id=id;
17 this.age=age;
18
19
20 }
21
22 public String getName() {
23 return name;
24 }
25
26 public void setName(String name) {
27 this.name = name;
28 }
29
30 public int getId() {
31 return id;
32 }
33
34 public void setId(int id) {
35 this.id = id;
36 }
37
38 public int getAge() {
39 return age;
40 }
41
42 public void setAge(int age) {
43 this.age = age;
44 }
45
46 }
47

 

posted on 2010-07-14 00:42  KuSiuloong  阅读(1330)  评论(1编辑  收藏  举报