首页 > 代码库 > [转]MySQL的简单使用和JDBC示例

[转]MySQL的简单使用和JDBC示例

MySql简单操作

//启动mysqlnet start mysql//登陆mysql -u root -p//创建建数据库create database mydb;create database test;//删除数据库drop database test;//使用数据库use mydb;//创建表create table mytable(name varchar(20),sex char);//显示数据库中所有表show tables;//增加一列alter table mytable add age int;//插入insert mytable value("liu",‘f‘,22);insert mytable value("wang",‘m‘,22);insert mytable(name,sex) value("li",‘f‘);insert mytable value("zhao",‘m‘,22);//删除表中项delete from mytable where name=”liu“;delete from mytable where name=”li“;//更新update mytable set age = 23 where name = "wang";//查询select * from mytable;

JDBC

  • JDBC驱动程序分为4类
    • JDBC-ODBC桥
    • 部分本地API,部分Java驱动程序
    • JDBC网络纯Java驱动程序
    • 本地协议Java驱动程序

JDBC的示例

import java.sql.*;import com.mysql.jdbc.Driver;public class JDBCMySql {        public void operateMySql() throws SQLException, ClassNotFoundException{                String driverName ="com.mysql.jdbc.Driver";        String URL = "jdbc:mysql://127.0.0.1:3306/mydb";        String sql = "SELECT * FROM mydb.mytable";        String username = "root";        String password = "";        Connection conn = null;        try{                //加载驱动        Driver.class.forName(driverName);                //建立连接        conn = DriverManager.getConnection(URL,username,password);                //创建statement来执行sql语句        Statement ps =  conn.createStatement();                //结果集处理        ResultSet rs = ps.executeQuery(sql);        while(rs.next()) {                System.out.println(rs.getString("name")+","+rs.getString("sex")+","+rs.getInt("age"));                }        }        catch (ClassNotFoundException e) {            e.printStackTrace();        }         catch(SQLException e){            e.printStackTrace();        }                //关闭连接        finally{            if(conn!=null){                try{                    conn.close();                }catch(SQLException e){                    e.printStackTrace();                }            }        }       }   }

建立一个test case来验证一下

import static org.junit.Assert.*;import java.sql.SQLException;import org.junit.Before;import org.junit.Test;public class JDBCTest {    @Test    public void test() throws ClassNotFoundException, SQLException {        JDBCMySql jm = new JDBCMySql();        jm.operateMySql();    }}

执行结果

技术分享

技术分享

转自:http://www.cnblogs.com/sweiqi/p/5936914.html;

[转]MySQL的简单使用和JDBC示例