Java连接mysql数据库
在java中连接mysql数据库,先要下载mysql驱动mysql-connector-java-5.1.30.zip,解压出.jar文件复制到项目目录中,再Build
Path即可使用。
package cn.hitech.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MysqlDemo { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.jdbc.Driver"); try { connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/unit", "root", "adminsa"); if (connection != null && !connection.isClosed()) { System.out.println("connection successfully."); statement = connection.createStatement(); statement .execute("INSERT INTO uinit(uid,uname,secret) VALUES(2,‘祁连山‘,‘secret3‘"); resultSet = statement.executeQuery("select * from uinit"); while (resultSet.next()) { System.out.println("uid" + resultSet.getString("uid")); System.out.println("uname" + resultSet.getString("uname")); System.out.println("secret" + resultSet.getString("secret")); } } } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } finally { resultSet = null; } try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } finally { connection = null; } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。