当前位置:Gxlcms > 数据库问题 > java与数据库连接的几个步骤

java与数据库连接的几个步骤

时间:2021-07-01 10:21:17 帮助过:2人阅读

public class mysqlTest { public static void main(String[] args) { new mysqlTest().start(); } public void start() { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://127.0.0.1:3306/mybase";//mybase为数据库名称 String user = "root"; String password = "rootpassword"; try { Class.forName(driver).newInstance(); // 尝试连接数据库 Connection conn = DriverManager.getConnection(url, user, password); if (!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"); // 编译数据库语句 Statement statement = conn.createStatement(); String sql = "select * from IDinformation"; ResultSet rs = statement.executeQuery(sql); String name = null; while (rs.next()) { name = rs.getString("id"); System.out.println(name + "\t" + rs.getString("secret")); } rs.close(); conn.close(); } catch (ClassNotFoundException e) { System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }

6.每个人的电脑环境和软件都有差异,不要想一次就能把事情做好,要多多尝试。

容易出问题的就是第2、3步和代码的编写。

java与数据库连接的几个步骤

标签:

人气教程排行