创建完毕如图:
在jdbc.properties文件中输入如下信息,分别是数据库的驱动,连接,用户名和密码
新建JdbcTest2.java类
输入如下代码:
代码说明:
这段代码是读取配置文件,把配置文件中的各个项通过名称读取出来
这段代码是通过反射来创建Driver对象,反射就是类的实例化
在主函数中输入如下,测试方法
运行之后的结果如下,表示连接成功!
package dataBaseimport java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import java.sql.ResultSet
//import java.sql.ResultSetMetaData
import java.sql.SQLException
import java.util.ArrayList
import java.util.List
public class DBHelper {
private Connection con
private PreparedStatement pstmt
private ResultSet rs
//静态语句块,加载驱动
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
} catch (ClassNotFoundException e) {
e.printStackTrace()
}
}
public ArrayList findBySql(String sql, ArrayList<String>params, Class<?>c) {
con = this.getCon()
try {
pstmt=con.prepareStatement(sql)
doParams(pstmt, params)
rs=pstmt.executeQuery()
while(rs.next()){
/**************************************************/
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return List
}
//连接数据库
public Connection getCon() {
try {
con = DriverManager.getConnection(
"jdbc:sqlserver://192.168.2.30:1433databaseName=数据库名",
"连接数据库名", "密码")
} catch (SQLException e) {
e.printStackTrace()
}
return con
}
//关闭所有连接
public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con) {
if (rs != null) {
try {
rs.close()
} catch (SQLException e) {
e.printStackTrace()
}
}
if (pstmt != null) {
try {
pstmt.close()
} catch (SQLException e) {
e.printStackTrace()
}
}
if (con != null) {
try {
con.close()
} catch (SQLException e) {
e.printStackTrace()
}
}
}
//对数据进行增、删、改
// insert into xx values(?,?)params={"张三","a"}
public void doUpdate(String sql, List<String>params) {
con = this.getCon()
try {
pstmt = con.prepareStatement(sql)
doParams(pstmt, params)
pstmt.executeUpdate()
} catch (SQLException e) {
e.printStackTrace()
} finally {
closeAll(null, pstmt, con)
}
}
public void doParams(PreparedStatement pstmt, List<String>params)
throws SQLException {
if (pstmt != null &&params != null &&params.size() >0) {
for (int i = 0i <params.size()i++) {
pstmt.setString(i + 1, params.get(i))
}
}
}
}
只需要mysql的驱动包:包名为:mysql-connector-java-5.1.37-bin.jar源码如下:
import java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import org.junit.Test
public class JdbcMysql {
@Test
public void connection() throws Exception{
String username = "root"
String password = "root"
String url = "jdbc:mysql://localhost:3306/exam?characterEncoding=utf-8"
String sql = "UPDATE s_cust SET cust_name=? WHERE cid = ? "
//加载mysql的驱动类,获得连接,获取SQL的预编译,设置参数,执行SQL语句
Class.forName("com.mysql.jdbc.Driver")
Connection con = DriverManager.getConnection(url, username, password)
PreparedStatement ps = con.prepareStatement(sql)
ps.setString(1, "北京")
ps.setInt(2, 6)
ps.execute()
ps.close()
con.close()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)