zoukankan      html  css  js  c++  java
  • Document

    今天突然心血来潮,想要用java连接mysql,记得以前是在vs2010的环境下用C#连接sql sever,其实他们的方法都差不多。

    现在就可以简单的介绍下java如何连接mysql

    第一步,设计mysql的数据库,设计数据库的时候特别要注意,数据库名是xsxx,表名字是xs。注意在设置字符的时候一定要选用utf8,不然就会以你不懂的形式出现。

    第二步:在esclip中新建项目,项目名称是TestJDBC,新建class名称为TestJDBC,添加引用项目文件

      第三步:项目中的相关代码:

       ——————————————————————————————————————————————————————————————————      

    /*****
    * java连接mysql
    * @author yanlong
    *2017/5/7
    */
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    //import java.util.Collection;
    import java.sql.SQLException;

    //import javax.sql.Statement;

    public class TestJDBC {
    public static void main(String[] args){
    ResultSet rs=null;
    Statement stmt=null;
    Connection conn=null;
    try{
    /*加载并注册mysql的JDBC驱动*/
    Class.forName("com.mysql.jdbc.Driver");
    /*建立到mysql的连接*/

    conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xsxx","root","123456");
    /*访问数据库,并执行sql语句*/

    stmt=conn.createStatement();

    rs=stmt.executeQuery("select *from xs");
    while(rs.next()){
    System.out.println(rs.getInt("id"));
    System.out.println(rs.getString("name"));
    System.out.println(rs.getString("major"));
    }
    }catch(ClassNotFoundException e){
    e.printStackTrace();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }finally{
    try{
    if(rs!=null){
    rs.close();
    rs=null;
    }
    if(stmt!=null){
    stmt.close();
    stmt=null;
    }
    if(conn!=null){
    conn.close();
    conn=null;
    }
    }catch(SQLException e){
    e.printStackTrace();

    }
    }
    }
    }

     ————————————————————————————————————————————————————————————

    第四步:直接运行项目,出现运行效果:

  • 相关阅读:
    「牛客练习赛53A」超越学姐爱字符串
    「CF52C」Circular RMQ
    「Luogu 2367」语文成绩
    「Luogu 1821」[USACO07FEB]银牛派对Silver Cow Party
    「POJ 3268」Silver Cow Party
    「Luogu 1349」广义斐波那契数列
    「CF630C」Lucky Numbers
    「Luogu 3792」由乃与大母神原型和偶像崇拜
    排序机械臂
    P2587 [ZJOI2008]泡泡堂
  • 原文地址:https://www.cnblogs.com/chenyanlong/p/6822759.html
Copyright © 2011-2022 走看看