将Java连接到MySQl数据库

发布于 2024-11-03 14:47:56 字数 57 浏览 1 评论 0原文


是否有一种标准方法可以将 Java 程序连接到 MySQL 数据库,哪种方法是最简单的?


Is there a standard way to connect a Java program to a MySQL database, and which is the easiest one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

病毒体 2024-11-10 14:47:56

除了上面发布的答案之外,一旦您跨越了称为学习曲线的初始障碍(并且在您遇到称为性能优化的下一个障碍之前),JPA(Hibernate)甚至会变得更容易。严肃地说,是的,JPA 也是一种以相同方式连接和查询几乎任何数据库的标准方法。

In addition to answer posted above, JPA (Hibernate) is even easier one once you cross the initial barrier called learning curve (and before you are hit by next one called, Performance Optimization). On the serious note, Yes JPA is also a standard way to connect and query pretty much any database the same way.

JDBC 是标准方式。下面是连接MySQL数据库的java代码示例:

  Connection con = null;
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/";
  String db = "testdb";
  String dbUser = "root";
  String dbPasswd = "mysql123";
  try{
  Class.forName(driver);
  con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
  try{
  Statement st = con.createStatement();
  String sql = "DELETE FROM user WHERE email = '[email protected]'";
  int delete = st.executeUpdate(sql);
  if(delete >= 1){
  System.out.println("Row is deleted.");
  }
  else{
  System.out.println("Row is not deleted.");
  }
  }
  catch (SQLException s){
  System.out.println("SQL statement is not executed!");
  }
  }
  catch (Exception e){
  e.printStackTrace();
  }

JDBC is the standard way. Below is the sample java code to connect MySQL database:

  Connection con = null;
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/";
  String db = "testdb";
  String dbUser = "root";
  String dbPasswd = "mysql123";
  try{
  Class.forName(driver);
  con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
  try{
  Statement st = con.createStatement();
  String sql = "DELETE FROM user WHERE email = '[email protected]'";
  int delete = st.executeUpdate(sql);
  if(delete >= 1){
  System.out.println("Row is deleted.");
  }
  else{
  System.out.println("Row is not deleted.");
  }
  }
  catch (SQLException s){
  System.out.println("SQL statement is not executed!");
  }
  }
  catch (Exception e){
  e.printStackTrace();
  }
影子是时光的心 2024-11-10 14:47:56

也许使用 Hibernate 进行对象关系映射对您来说是一种有用的方法。

Maybe object-relational mapping with Hibernate is a useful way for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文