数据库技术-JDBC连接MySQL(二)

2014-11-24 10:40:14 · 作者: · 浏览: 1
ing password = "123"; String url = "jdbc:mysql://localhost:3308/zoo"; String url2 = "jdbc:mysql://192.168.1.115:3308/zoo"; String url3 = "jdbc:mysql://localhost:3308/zoo user=root&password=123&useUnicode=true&characterEncoding=8859_1"; String driver = "com.mysql.jdbc.Driver"; String tableName = "animal"; String sqlstr = "insert into animal (id,name,year) value("+5+","+"aiii"+","+33+");"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName(driver); conn = DriverManager.getConnection(url3, "root", "123"); stmt = conn.createStatement(); System.out.println("数据库连接成功!"); } catch (ClassNotFoundException e) { System.out.println("数据库驱动不存在!"); System.out.println(e.toString()); } catch (SQLException e) { System.out.println("SQL错误"); System.out.println(e.toString()); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e2) { System.out.println(e2.toString()); } } } }

\

连接成功!

三、总结

Jdbc 连接数据库不复杂,连接的模式已定义的很清晰,按照

Class.forName(“com.mysql.jdbc.Driver”) ->

DriverManager.getConnection ->

CreateStatement ->

rs进行操作

的方式就可以顺利进行。

注意容易出错的地方: DriverManager.getConnection 后面的写法比较多

1. String url = "jdbc:mysql://localhost:3308/zoo";

2. String url2 = "jdbc:mysql://192.168.1.115:3308/zoo";

3. String url3 = "jdbc:mysql://localhost:3308/zoo user=root&password=123&useUnicode=true&characterEncoding=8859_1";

这几种都可以,主要是端口不要错,一般没有问题!

提供点帮助文件吧:

mysql-essential-5.6.0 下载地址 http://download.csdn.net/detail/zhangty0223/6811589

提供一个学习资料:

mysql从零开始学part1: http://download.csdn.net/detail/zhangty0223/6811667

mysql从零开始学part2: http://download.csdn.net/detail/zhangty0223/6811695

java jdbc mysql 驱动:http://download.csdn.net/detail/zhangty0223/6819387

整个工程源码:http://download.csdn.net/detail/zhangty0223/6819457

谢谢!

2014.1.7