[color=olive]以MyEclipse为例,要连接MYSql数据库首先要安装mysql。在这就带过 不予介绍了。[/color]
在MyEclipse中首先要下载一个mysql-connection.jar包。在这最好是直接将这个jar包copy到项目的lib文件夹中。以便以后的移动到别的pc机上还要重新导入jar包。
1.加载驱动 Class.forName("com.mysql.jdbc.Driver");或者new
2.获得连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dataBaseName",userName,passWord);
3.Statement stmt = conn.createStatement();
获得结果集 ResultSet rs = stmt.executeQuery(sql);
或者用PreparedStatement pstmt = conn.createPreparedStatement(sql);注:这种一般用的是比较多的。安全性相对高点。
还有就是以上的代码都有可能产生异常,所以必须捕捉异常。另外用过以后要注意关闭自己所用的流。
[color=olive][/color][align=center][/align]下面是一个简单的连接数据库的代码:
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println("加载驱动错误,请查看连接数据库的代码!");
e.printStackTrace();
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "....";
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dataBaseName",userName,passWord);
pstmt = conn.PreparedStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
....
....
}
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try{
if(rs != null){
rs.close();
rs = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}catch(Exception e){
e.printStackTrace();
}
}
上面是一个简单的读取数据库的代码。
在MyEclipse中首先要下载一个mysql-connection.jar包。在这最好是直接将这个jar包copy到项目的lib文件夹中。以便以后的移动到别的pc机上还要重新导入jar包。
1.加载驱动 Class.forName("com.mysql.jdbc.Driver");或者new
2.获得连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dataBaseName",userName,passWord);
3.Statement stmt = conn.createStatement();
获得结果集 ResultSet rs = stmt.executeQuery(sql);
或者用PreparedStatement pstmt = conn.createPreparedStatement(sql);注:这种一般用的是比较多的。安全性相对高点。
还有就是以上的代码都有可能产生异常,所以必须捕捉异常。另外用过以后要注意关闭自己所用的流。
[color=olive][/color][align=center][/align]下面是一个简单的连接数据库的代码:
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println("加载驱动错误,请查看连接数据库的代码!");
e.printStackTrace();
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "....";
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dataBaseName",userName,passWord);
pstmt = conn.PreparedStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
....
....
}
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try{
if(rs != null){
rs.close();
rs = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}catch(Exception e){
e.printStackTrace();
}
}
上面是一个简单的读取数据库的代码。

被折叠的 条评论
为什么被折叠?



