当前位置: 移动技术网 > IT编程>数据库>Mysql > JDBC的连接mySql的基本知识

JDBC的连接mySql的基本知识

2018年09月03日  | 移动技术网IT编程  | 我要评论

  这只是我自己的随笔博客~,用于偶尔回忆知识,可能存在一些错误,如有错误,欢迎指正~

首先对于jdbc连接mysql,要了解基本的框架结构

画的比较烂,大约就是这样的结构

然后看一下具体实现的 代码:;

public class dbutil {
	private string user = "root";
	private string password = "root";
	private string url = "jdbc:mysql://localhost:3306/mydb6";
	private static dbutil dbutil;
	connection connection = null;

	// 单例:构造方法私有化
	private dbutil() {

	}

	public synchronized static dbutil getinstance() {
		if (dbutil == null) {
			dbutil = new dbutil();
		}
		return dbutil;
	}

	/**
	 * 创建数据库连接
	 */
	public connection getconnection() {
		if (connection == null) {
			try {
				// 注册驱动
				class.forname("com.mysql.jdbc.driver");
				// 获取连接
				connection = drivermanager.getconnection(url, user, password);
			} catch (classnotfoundexception e) {
				// todo auto-generated catch block
				e.printstacktrace();
			} catch (sqlexception e) {
				// todo auto-generated catch block
				e.printstacktrace();
			}
		}
		return connection;
	}
}

  上面这个是通过单例模式  建立了dbutil这样一个类。通过这个类可以干什么呢?可以实现----数据库的连接!

没错,connection接口的作用就是连接数据库-
与特定数据库的连接(会话)。在连接上下文中执行 sql 语句并返回结果。

怎样才能得到这个连接呢?--想要建立这个连接,你需要注册一个驱动---嗯~就是这个代码   class.forname("com.mysql.jdbc.driver");  

它是通过反射的机制来获得的,不了解反射?嗯~那你记住就完了 哈哈哈

connection = drivermanager.getconnection(url, user, password);这一句话的是用来获取连接的 ,这三个参数分别是   数据的地址,jdbc:mysql://ip地址:端口号/数据库的名称

嗯~然年再将一下如何通过jdbc向数据库写入数据

public int insertstubystatement() {
        string sql1 = "insert into stu(sname,sage) values('aaa',1)";
        string sql2 = "insert into stu(sname,sage) values('bbb',1)";
        string sql3 = "insert into stu(sname,sage) values('ccc',1)";
        connection connection = getconnection();// 获得数据库的连接
        statement stmt = null;
        try {
            stmt = (statement) connection.createstatement();
            connection.setautocommit(false);
            stmt.addbatch(sql1);//批量添加sql语句
            stmt.addbatch(sql2);//批量添加sql语句
            stmt.addbatch(sql3);//批量添加sql语句
            //一次性执行
            stmt.executebatch();
            connection.commit();
            system.out.println("批处理成功");
        } catch (sqlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (exception e2) {

            }
        }
        return i;
    }

这里使用的statement 来实现的,写出你要操作的 sql语句。(提一下,一般这些操作都是放在dbutil类中的额 ,这个方法我也是放在dbutil的)。

第二步:根据上面的定义的方法获取数据库。

下面就是获取一个statement 对象,然后通过这个对象的stmt.executebatch();就可以在数据库中执行刚才就的语句了,这样就做到了静态插入数据。

那动态插入数据是怎样的呢 ?-----那就是用到了另一个能够实现语句的对象preparedstatement

直接上代码吧 

public int insertstu(string sname,int sage){
        string sql = "insert into stu(sname,sage) values(?,?)";
        connection connection = getconnection();//获得数据库的连接
        preparedstatement ps = null;
        int i = 0;
        try {
            ps  = (preparedstatement) connection.preparestatement(sql);
            ps.setstring(1, sname);
            ps.setint(2, sage);
            
            i=ps.executeupdate();
        } catch (sqlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }finally {
            try {
                if (ps!=null) {
                ps.close();
                }
            } catch (exception e2) {
            
            }
        }
        return i;
    }

定义的插入方法有了两个参数的数值

与statement的区别在哪呢?--一个是sql字符串语句的区别,多了“?”,作用是---看下面这两行代码

 ps.setstring(1, sname);
 ps.setint(2, sage);
ps.set****(a,b)有两个参数,sql语句中也有两个?,所以参数a,代表的是sql语句的第几个“?”,如果参数是1,则说明sql语句中第一个“?”的位置替换为参数b,
如果 同理如果参数是2,则说明sql语句中第一个“?”的位置替换为参数b.这样就做到了动态的插入数据,我们只要在调用插入方法的时候传入想要插入的数据就好了,不用每次都写新的sql语句。
对于 i=ps.executeupdate();语句,它返回的这次你的数据库操作后有有几条数据有影响.这种方法对于插入,当然是i=1了

但是对于产出和修改的就不是一定了,删除修改我直接贴代码了就不再做讲解
//修改
public int updatestu(int sage,string sname){ string sql = "updae stu set sage = ? where sname = ?"; connection connection = getconnection(); preparedstatement ps =null; int i = 0; try { ps = (preparedstatement) connection.preparestatement(sql); ps.setint(1, sage); ps.setstring(2, sname); i = ps.executeupdate(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); }finally { try { if (ps!=null) { ps.close(); } } catch (exception e2) { } } return i; } //删除 public int deletestu(string sname,int sage) { string sql = "delete from stu where sname=? and sage = ?"; connection conn = getconnection();//获得数据库连接 preparedstatement ps = null; int i = 0; try { ps = (preparedstatement) conn.preparestatement(sql); ps.setstring(1, sname); ps.setint(2,sage ); i = ps.executeupdate(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); }finally { try { if(ps != null) ps.close(); }catch (exception e) { // todo: handle exception } } return i; }

 

数据库最重要的是什么---查询数据,相对于增删改--查可能稍微繁琐一点
代码如下:
/**
     * 查询所有学生
     * @return
     */
    public arraylist<stu> querystu(){
        string sql = "select * from stu ";// select *  或的字段的顺序和数据库中的是一致
        connection conn = getconnection();
        preparedstatement ps = null;
        resultset rs = null;
        arraylist<stu> stus = new arraylist<stu>();//此集合用于存储每一个学生对象
        try {
            ps = (preparedstatement) conn.preparestatement(sql);
            rs = ps.executequery();
            //遍历rs
            while(rs.next()) {//true表示有下一条数据
                int id = rs.getint("id");
                string sname = rs.getstring("sname");
                int sage = rs.getint("sage");
                //创建stu对象
                stu stu = new stu(id, sname, sage);
                //收集对象
                stus.add(stu);
            }
        } catch (sqlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }finally {
            try {
                if(rs != null)
                    rs.close();
                if(ps != null)
                    ps.close();
            }catch (exception e) {
                // todo: handle exception
            }
        }
        
        return stus;
    }

讲一下重点的地方     resultset rs = null;  这个对象存储的一个查询的结果集合。select * from stu这个返回的 应该是查询的学生表中每个学生的所有数据,

所以rs就可以储存这样的一个集合,然后通过遍历得到其中的数据,将数据赋值给一个学生对对象,将对象加入到集合中,就得到可表中所有的数据~

 

这次讲的主要是基础部分,等下次继续探讨jdbc联合其他的一些操作~


class.forname("com.mysql.jdbc.driver");

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网