今天准备用java写一个管理密码用的小软件来练练手,数据库准备用mysql,因为只安装了这一个,
java连接mysql用到了驱动JDBC
下载地址 http://mysql.cs.pu.edu.tw/Downloads/Connector-J/mysql-connector-java-5.1.2-beta.zip下载MYSQL5.1的JDBC驱动程序,解压缩到你放JDBC驱动程序的位置就可以了,不需要安装。然后设置Classpath环境变量,在Classpath环境变量里添加JDBC驱动程序,如我的是添加D:\JDBC_Driver\mysql\mysql-connector-java-5.1.2-beta\mysql-connector-java-5.1.2-beta-bin.jar。
如果这样还是找不到驱动的话,那么就右击你的工程选择最后一项properties ,然后在library中添加jdbc的jar,这样就可以了
下面是java的基本连接数据库的代码
1:import java.sql.Connection;
2:import java.sql.DriverManager;
3:import java.sql.ResultSet;
4:import java.sql.ResultSetMetaData;
5:import java.sql.SQLException;
6:import java.sql.Statement;
7:
8:publicclass sql {
9:
10:/**
11: * 12 * @param args 13
12: */
13:publicstaticvoid main(String[] args) {
14: String user = "root";
15: String password = "6191080";
16: String url = "jdbc:mysql://localhost:3306/gglg";
17: String driver = "com.mysql.jdbc.Driver";
18:// String driver = "org.gjt.mm.mysql.Driver";
19: String tableName = "article";
20: String sqlstr;
21: Connection con = null;
22: Statement stmt = null;
23: ResultSet rs = null;
24:try {
25: Class.forName(driver);
26:// connect to the sql
27: con = DriverManager.getConnection(url, user, password);
28:// statement to do the sql
29: stmt = con.createStatement();
30:// insert to the database
31:// sqlstr =
32:// "insert into "+tableName+"(title,author) values ('2000','honey')";
33:// stmt.executeUpdate(sqlstr);
34:
35: sqlstr = "select * from " + tableName;
36://execute the sql statement return rs
37: rs = stmt.executeQuery(sqlstr);
38:
39: ResultSetMetaData rsmd = rs.getMetaData();
40:
41: System.out.print(rsmd.getColumnName(1)+"\t");
42: System.out.print(rsmd.getColumnName(2)+"\t");
43: System.out.println(rsmd.getColumnName(3));
44:int j = 0;
45://get column counts
46: j = rsmd.getColumnCount();
47:
48:while (rs.next()) {
49:for (int i = 0; i < j; i++) {
50: System.out.print(rs.getString(i + 1));
51: System.out.print("\t");
52: }
53: System.out.println();
54: }
55: } catch (ClassNotFoundException e1) {
56: System.out.println("数据库驱动不存在!");
57: System.out.println(e1.toString());
58: } catch (SQLException e2) {
59: System.out.println("数据库存在异常!");
60: System.out.println(e2.toString());
61: } finally {
62:try {
63:if (rs != null)
64: rs.close();
65:if (stmt != null)
66: stmt.close();
67:if (con != null)
68: con.close();
69: } catch (SQLException e) {
70: System.out.println(e.toString());
71: }
72: }
73: }
74: }