第一次用数据库,eclipse+mysql

Eclipse连接mysql

首先,按照http://tech.163.com/06/0125/10/28A9DCO10009158J.html上面的提示安装配置好java环境和mysql环境。

然后根据http://database.51cto.com/art/201006/204217.htm上面的提示,和代码一步一步地往后做。

其中,先要在eclipse中工程右键,选择Properties,再选择Java Biuld Path,选择Add External JARs…,然后选择载下来的数据库驱动。类似于mysql-connector-java-5.1.21-bin.jar的文件。

再把代码贴进去,就能正常运行了。

import java.sql.*;

public class sql
{
   public static void main(String args[]){
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://127.0.0.1:3306/sakila";
      String user = "root";
      String password = "root";
      try{
         Class.forName(driver);
         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 sakila.table;";
         ResultSet rs = statement.executeQuery(sql);  
         System.out.println("-----------------");  
         System.out.println("执行结果如下所示:");  
         System.out.println("-----------------");  
         System.out.println(" 学号" + "\t" + " 姓名");  
         System.out.println("-----------------");  
         String name = null;  
         while(rs.next()) { name = rs.getString("id");

      // 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。

      // 然后使用GB2312字符集解码指定的字节数组

      name = new String(name.getBytes("ISO-8859-1"),"GB2312");

      // 输出结果

      System.out.println(rs.getString("tablecol") + "\t" + name);  
      }  
      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();   
      }   
   }
}

运行结果:

Succeeded connecting to the Database!
-----------------
执行结果如下所示:
-----------------
学号 姓名
-----------------
sd sdgs
wew we

其中学号姓名在数据库中的变量名和值是乱设的,由于代码是直接copy的就只改了个变量名==#

原文地址:https://www.cnblogs.com/zhidian314/p/2601515.html