您的位置:首页 > 编程语言 > Java开发

JAVA学习笔记 -- JDBC及其应用

2014-06-23 10:26 387 查看
一、准备工作

1、开启SQL Server服务和启用TCP/IP  并且确认TCP端口



2、Eclipse下给项目导入sqljdbc4.jar包

将下载好的 sqljdbc_4.0.2206.100_chs.exe运行解压。然后在 .\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\chs\auth
路径下选择合适版本的sqljdbc_auth.dll, 将其放在 C:\Windows\System32下。

给项目导入包:右键你的项目选择Properties,弹出下面窗口,选择Java Build Path

通过右边的一些Add操作导入,选择Add JARs要把sqljdbc4.jar包放在项目目录下面。

二、连接数据库(SQL Server)

String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=LG";
Class.forName(driverName);//装载这个类
//dbConn = DriverManager.getConnection(dbURL);//Windows身份认证
tring username = "sa";
String password = "xxxx";
dbConn = DriverManager.getConnection(dbURL,username,password);


三、操作数据库

1、ResultSet类对数据库的操作

Statement st = dbConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,//对数据敏感
ResultSet.CONCUR_UPDATABLE);//可更新
String sql = "select * from student ";
ResultSet result = st.executeQuery(sql);
//更新第1行name字段
result.absolute(1);
result.updateString("name","lg");
result.updateRow();
//插入一条记录
result.moveToInsertRow();
result.updateString(1, "ln");
result.updateString(2, "男");
result.updateInt(3,12);
result.updateInt(4,80);
result.insertRow();
result.moveToInsertRow();
//删除一条记录
result.last();
result.deleteRow();
result.absolute(0);
st.close();//先关闭对话
dbConn.close();//再关闭连接


2、将连接数据库信息保存到driver.properties的文件里,再用一个getProperty()方法获取信息

driver.properties文件:

drivers=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;DatabaseName=LG
user=sa
password=xxxx
注意:文件要放在项目的根目录下面,而且=号两边不能有多余空格

getProperty()方法:

public void getProperty() {
Properties prop = new Properties();
try {
FileInputStream in = new FileInputStream("driver.properties");
prop.load(in);
driverName = prop.getProperty("drivers");
url = prop.getProperty("url");
userName = prop.getProperty("user");
passWord = prop.getProperty("password");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


3、事务处理

将数据库自动提交设为false,执行一段sql语句,在con.commit();前还可以通过con.rollback();回到未执行sql语句之前的状态。

<pre name="code" class="cpp">con.setAutoCommit(false);
st.executeUpdate(sql);
con.rollback();
con.commit();
con.setAutoCommit(true);




4、预查询

String sql = " select 姓名,学号,专业,籍贯 from student where 姓名 = ?";
PreparedStatement pre = con.prepareStatement(String sql);
pre.setString(1,"张强");
ResultSet re = pre.executeQuery();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息