• Linux 下使用Java连接MySQL数据库,并且实现插入、删除、选择操作


    实验环境:

            OS : CentOS5.5 (Linux)

            IDE : Eclipse

            DBMS : MySQL

    准备工作:

            1、安装 MySql 。

           详见http://www.cnblogs.com/zyumeng/archive/2012/09/17/2688772.html

            2、安装 JDBC :

          在命令行中输入:

          wegt http://www.mysql.com/downloads/connector/j/mysql-connector-java-5.1.22.tar.gz

          tar xzvf mysql-connector-java-5.1.22.tar.gz

            3、将 mysql 服务器启动起来:

         service mysqld start 

            4、登陆服务器以建立数据库:

         mysql –u root –ppassword  

            5、建立数据库:

         create database Data;  

              然后即可在 IDE (Eclipse)下实现连接。    

            6、在Eclipse建立项目,然后 将驱动加载到该项目上。 

              方法为 : 点击项目右键 ->Properties( 属性 )->Java Build Path->Libraries->Add External JARs :

               选择“解压JDBC目录”/mysql-connector-java-5.1.15.jar 

     

    在Eclipse中建立Java文件,命名为DataBase.java

    具体代码:

    [java] view plaincopy

    1. import java.io.UnsupportedEncodingException ;  
    2. import java.sql.Connection ;  
    3. import java.sql.DriverManager ;  
    4. import java.sql.PreparedStatement ;  
    5. import java.sql.ResultSet ;  
    6. import java.sql.SQLException ;  
    7. import java.sql.Statement ;  
    8. public class DataBase  
    9. {  
    10.      public static final String driver = "com.mysql.jdbc.Driver" ; // 驱动  
    11.      public static final String url = "jdbc:mysql://localhost:3306/Data" ;// 定义URL  
    12.      public static final String user = "root" ; // 用户名字  
    13.      public static final String password = "password" ; // 用户密码  
    14.        
    15.      private static Connection connection ;// 用于建立连接  
    16.      private static Statement statement ;// 用于执行  
    17.        
    18.      public static void main( String[] args ) throws ClassNotFoundException ,  
    19.              SQLException , UnsupportedEncodingException  
    20.      {  
    21.          connect() ;// 先和数据库服务器建立连接  
    22.          createTable() ;// 建立表  
    23.          insert() ;// 向表中插入值  
    24.          query() ;// 查询  
    25.          close() ;// 关闭连接  
    26.      }  
    27.        
    28.      /** 
    29.       * @throws ClassNotFoundException 
    30.       * @throws SQLException 
    31.       *             此方法建立连接 
    32.       */  
    33.      private static void connect() throws ClassNotFoundException , SQLException  
    34.      {  
    35.            
    36.          Class.forName( driver ) ;  
    37.          connection = DriverManager.getConnection( url , user , password ) ;// 建立连接  
    38.          if( !connection.isClosed() )  
    39.          {  
    40.              System.out.println( "Succeeded connecting to the Database!" ) ;  
    41.          }  
    42.          statement = connection.createStatement() ;// 建立statement  
    43.      }  
    44.        
    45.      /** 
    46.       * @throws SQLException 
    47.       *             建立表 
    48.       */  
    49.      private static void createTable() throws SQLException  
    50.      {  
    51.          String sql = "create table Student( Id char(20) not null , Name char(20) not null , Sex char(10) not null , Mail char(30) not null , Adress char(30) not null , primary key(Id) ) ENGINE=InnoDB   DEFAULT   CHARSET=utf8 ;" ;  
    52.          statement.executeUpdate( "drop table if exists Student ;" ) ;// 如果该表已经有了则删除  
    53.          statement.executeUpdate( sql ) ;// 建立表  
    54.      }  
    55.        
    56.      /** 
    57.       * @throws UnsupportedEncodingException 
    58.       * @throws SQLException 
    59.       *             插入值 
    60.       */  
    61.      private static void insert() throws UnsupportedEncodingException ,  
    62.              SQLException  
    63.      {  
    64.          // 声明常量  
    65.          String[] ids = { "123" , "456" , "789" } ;  
    66.          String[] names = { "张三" , "李四" , "王五" } ;  
    67.         String[] sexs = { "女" , "男" , "男" } ;  
    68.          String[] mails = { "123@qq.com" , "456@qq.com" , "789@qq.com" } ;  
    69.          String[] addresses = { "北京" , "上海" , "深圳" } ;  
    70.            
    71.          String id = null , name = null , sex = null , mail = null , address = null ;  
    72.          String sql = "insert into Student( Id , Name , Sex , Mail , Adress ) values( ? , ? , ? , ? , ? ) ;" ;  
    73.          PreparedStatement preparedStatement = connection.prepareStatement( sql ) ;  
    74.          forint i = 0 ; i < 3 ; ++ i )  
    75.          {  
    76.              id = ids[ i ] ;  
    77.              name = new String( names[ i ].getBytes( "gbk" ) , "ISO-8859-1" ) ;// 因为中文会出现乱码,因此先转码  
    78.              sex = new String( sexs[ i ].getBytes( "gbk" ) , "ISO-8859-1" ) ;  
    79.              mail = mails[ i ] ;  
    80.              address = new String( addresses[ i ].getBytes( "gbk" ) ,  
    81.                      "ISO-8859-1" ) ;  
    82.                
    83.              preparedStatement.setString( 1 , id ) ;  
    84.              preparedStatement.setString( 2 , name ) ;  
    85.              preparedStatement.setString( 3 , sex ) ;  
    86.              preparedStatement.setString( 4 , mail ) ;  
    87.              preparedStatement.setString( 5 , address ) ;  
    88.              preparedStatement.executeUpdate() ;// 执行  
    89.          }  
    90.      }  
    91.        
    92.      /** 
    93.       * @throws SQLException 
    94.       * @throws UnsupportedEncodingException 
    95.       *             查询 
    96.       */  
    97.      private static void query() throws SQLException ,  
    98.              UnsupportedEncodingException  
    99.      {  
    100.          String query = "select * from Student" ;  
    101.          ResultSet resultset = null ;  
    102.            
    103.         resultset = statement.executeQuery( query ) ;// 先将结果保存到resultset中  
    104.            
    105.          System.out.println( "Id/tName/tSex/tMail/t/tAddress" ) ;  
    106.          System.out  
    107.                  .println( "---------------------------------------------------------------" ) ;  
    108.          // 将结果读出来  
    109.          while( resultset.next() )  
    110.          {  
    111.              String id = resultset.getString( "Id" ) ;  
    112.              String name = new String( resultset.getString( "Name" ).getBytes(  
    113.                      "ISO-8859-1" ) , "gbk" ) ;// 将码再转回来,以防乱码  
    114.              String sex = new String( resultset.getString( "Sex" ).getBytes(  
    115.                      "ISO-8859-1" ) , "gbk" ) ;  
    116.              String mail = resultset.getString( "Mail" ) ;  
    117.              String address = new String( resultset.getString( "Adress" )  
    118.                      .getBytes( "ISO-8859-1" ) , "gbk" ) ;  
    119.              System.out.println( id + "/t" + name + "/t" + sex + "/t" + mail  
    120.                      + "/t" + address ) ;  
    121.          }  
    122.          System.out  
    123.                  .println( "---------------------------------------------------------------" ) ;  
    124.      }  
    125.        
    126.      /** 
    127.       * @throws SQLException 
    128.       *             关闭连接 
    129.       */  
    130.      private static void close() throws SQLException  
    131.      {  
    132.          statement.close() ;// 关闭statement  
    133.          connection.close() ;// 关闭连接  
    134.      }  
    135.        

    136. }  

    已验证上述程序正确

    参考资料:

    http://blog.csdn.net/shiyanhui66/article/details/6382483

    《MySQL快速入门》 第18章 清华大学出版社

  • 相关阅读:
    SpringCloud与SpringBoot区别
    Spring cloud概念
    微服务框架对比
    期末作品检查
    管理信息系统 第三部分 作业
    作业38——模型分离(选做)
    作业37——密码保护
    作业36——实现搜索功能
    作业35——完成个人中心—导航标签
    作业34——个人中心标签页导航
  • 原文地址:https://www.cnblogs.com/zyumeng/p/2716370.html
Copyright © 2020-2023  润新知