连接mysql数据库2+操作入门

package 对数据库操作Statment;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class query {
    /**
     * query
     * 
     * @throws Exception
     */
    @Test
    public void query() throws Exception {
        // 声明ststment对象用语执行sql
        Statement st = con.createStatement();
        // sql
        String sql = "select * from stud";
        // 查询返回结果集
        ResultSet rs = st.executeQuery(sql);
        // 遍历
        while (rs.next()) {

            String id = rs.getString("id");
            String name = rs.getString("name");
            System.err.println("编号:" + id + "," + "姓名" + name);

        }

    }

    /**
     * 删除
     * 
     * @throws Exception
     */
    @Test
    public void del() throws Exception {
        Scanner sc = new Scanner(System.in);
        System.err.println("plz enter id for del:");
        String id = sc.nextLine();

        Statement st = con.createStatement();
        String sql = "delete from stud where id=" + id;
        System.err.println("sql is:" + sql);
        st.executeUpdate(sql);
    }

    /**
     * save
     * 
     * @throws Exception
     */
    @Test
    public void save() throws Exception {
        Scanner sc = new Scanner(System.in);
        System.err.println("输入id");
        String id = sc.nextLine();
        System.err.println("输入name");
        String nm = sc.nextLine();
        Statement st = con.createStatement();
        String sql = "insert into stud values(" + id + ",'" + nm + "')";
        System.err.println("sql is:" + sql);
        st.executeUpdate(sql);

    }

    @Before
    // 执行Test前执行
    public void getCon() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/abc?useUnicode=true&characterEncoding=utf8";
        con = DriverManager.getConnection(url, "root", "1234");
        // con.close();
        // System.err.println(con);

    }

    @After
    // 执行Test后执行
    public void closeConn() throws Exception {
        if (con != null || !con.isClosed()) {

            con.close();
        }

    }

    private Connection con;

}
posted @ 2014-04-23 20:47  夏微风  阅读(186)  评论(0编辑  收藏  举报