⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jdbc_mysql.java

📁 java通过JDBC连接My SQL
💻 JAVA
字号:
/**
 *2007-4-20
 *下午12:21:19
 */

/**
 * @author linden
 *
 */
import java.sql.*;
public class JDBC_MYSQL {
	public static Connection getConnection() throws SQLException,
	   java.lang.ClassNotFoundException {
	  //取得连接的url
	  String url = "jdbc:mysql://localhost:3306/chengji";
	  //加载MySQL的jdbc驱动
	  Class.forName("com.mysql.jdbc.Driver");
	  //使用能访问MySQL数据库的用户名root
	  String userName = "root";
	  //使用口令
	  String password = "";
	  //打开数据库连接
	  Connection con = DriverManager.getConnection(url, userName, password);
	  return con;
	 }

	 public static void main(String args[]) {
	  try {
	   //取得数据库的连接
	   Connection con = getConnection();
	   //创建一个声明,用来执行sql语句
	   Statement sql = con.createStatement();
	   //如果同名数据库存在,删除掉
	   //sql.executeUpdate("drop table if exists score");
	   //执行了一个sql语句生成了一个名为score的表
	   //sql
	   //  .executeUpdate("create table score (name varchar(20) not null default 'name',english int not null default 60); ");
	   //向表中插入数据
	   //sql.executeUpdate("insert into score values('liyinglin',98)");
	   //sql.executeUpdate("insert into score values('jiangshan',79)");
	   //sql.executeUpdate("insert into score values('wangjiawu',100)");
	   //sql.executeUpdate("insert into score values('xingweiqi',89)");
	   //sql.executeUpdate("insert into score values('lingsheng',61)");
	   //执行查询数据库的sql语句
	   String query = "select * from score";
	   //String query = "select * from score where english>=80";
	   //返回一个结果集
	   ResultSet result = sql.executeQuery(query);
	   System.out.println("MYSQL中成绩表数据如下:");
	   //使用了一个while循环打印出了score表中的所有的数据
	   System.out.println("--------------------");
	   System.out.println("姓名" + "   " + "英语成绩");
	   System.out.println("--------------------");
	   while (result.next()) {
	    String name = result.getString("name");
	    String mathScore = result.getString("english");
	    //取得数据库中的数据
	    System.out.println(name + "  "  + mathScore);

	   }
	   //关闭声明和连接
	   sql.close();
	   result.close();
	   con.close();

	  } catch (java.lang.ClassNotFoundException e) {
	   System.err.print("ClassNotFoundException: ");
	   //加载jdbc错误,所要用的驱动没找到
	   System.err.println(e.getMessage());
	   //其他错误
	  } catch (SQLException ex) {
	   System.err.println("SQLException: " + ex.getMessage());
	   //显示数据库连接错误或者查询错误
	  }

	 }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -