Java JDBC连接数据库 将数据库连接封装成函数

package com.Test;

import java.sql.*;


public class test1 {
	public static Connection getConnection() throws SQLException, ClassNotFoundException{
		Class.forName("com.mysql.jdbc.Driver");
		String url="jdbc:mysql:///test?useSSL=true";
		return DriverManager.getConnection(url, "root", "root");
	}
	public static boolean executeDML(String sql,Object[] args) throws ClassNotFoundException, SQLException{
		Connection conn=getConnection();
		PreparedStatement pstmt=conn.prepareStatement(sql);
		for(int i=0;i0)
			return true;
		else
			return false;
	}
	public static  void main(String[] args) throws ClassNotFoundException, SQLException {
		String sql="insert into users(name,sex,age,addr) values(?,?,?,?)";
		Object[] myargs={"李凯","男","20","成都"};
		if(executeDML(sql, myargs)){
			System.out.println("插入成功");
		}else{
			System.out.println("插入失败");
		}
	}
}

 

你可能感兴趣的:(Java学习)