JDBC连接mysql数据库,添加数据

如下:其中添加/删除/修改只是sql字符串不同

//3.要执行的字符串
String sql="INSERT INTO t_student(NAME,age,email) VALUES('xxx','22','kangqing.37@gmail.com')";

//String sql="DELETE FROM t_student where id=2";

//String sql="UPDATE t_student set name='twzd',age='100',email='000' where id=7";

 
package com.hx.jdbc.connection;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

import org.junit.Test;

import junit.framework.TestCase;

public class JDBCText extends TestCase {
    /**
     * 向数据库中添加一条数据
     * 
     * statement:用于执行sql语句的对象
     * 用connection的createStatement()方法获取
     * 用executeUpdate(sql)执行sql语句
     * 注意:只能执行 insert,update,delect,不能执行select
     * @throws Exception
     */
    @Test
    public void testStatement() throws Exception{
        //1.调用getConnection2数据库连接方法
        Connection conn=null;
        Statement statement=null;
        
        try {
            conn=getConnection2();
            //3.要执行的字符串
            String sql="INSERT INTO t_student(NAME,age,email) VALUES('xxx','22','kangqing.37@gmail.com')";
            System.out.println(sql);
            //4.执行sql
            statement=conn.createStatement();
            statement.executeUpdate(sql);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                if(statement!=null)
                    statement.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                //2.关闭数据库
                if(conn!=null)
                    conn.close();
            }
            
        }
        
        
    }
    /**
     * 连接数据库的方法
     * @return
     * @throws Exception
     */
    @Test
    public Connection getConnection2() throws Exception{
        //1.创建数据库的4个字符串
        
        //2.创建Properties对象
        Properties pro=new Properties();
        //3.获取jdbc.pro对应的输入流
        InputStream in=
                this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        //4.加载输入流
        pro.load(in);
        //5.具体决定4个字符串的值
        String driver=pro.getProperty("driver");
        String jdbcUrl=pro.getProperty("jdbcUrl");
        String user=pro.getProperty("user");
        String password=pro.getProperty("password");
        //6.加载数据库驱动程序
        Class.forName(driver);
        //7.通过DriverManager的getConnection()方法获取数据库连接
        Connection conn=DriverManager.getConnection(jdbcUrl, user, password);
        return conn;
    }
}

 

其中数据库信息写在配置文件jdbc.properties中,如下所示:

 

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/students
user=root
password=5678

 

posted @ 2016-12-05 15:31  云晴  阅读(2271)  评论(0编辑  收藏  举报