JDBC连接
当之前的环境都配置好了之后,就可以开始在java中连接数据库了,我用的是sqlserver 2005,所以我在这里展示sqlserver 2005 的连接方式,其他的同理
首先
导入jdbc的驱动包,使用的数据库是什么就导入什么,右击文件夹
然后选中导入的驱动包,然后Apply and Close 导入之后就可以在java中实现连接操作了
代码
我把它进行了封装,封装为一个工具
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class jdbcUtil {
Connection con = null;
PreparedStatement ps1 =null;
ResultSet rs = null;
InputStream is=null;
OutputStream os= null;
public static Connection getMysqlConn(String name,String pwd) {//这里传入账号密码
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名",name,pwd);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//关闭
public static void close(ResultSet rs,Statement ps,Connection con) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
就行了