一、用Java连接SQL Server数据库
java可以通过JDBC连接SQLServer(版本一般为2012),在连接之前首先要做一些准备工作,准备工作参考下面网站(一句一句看,真的很有帮助!)http://blog.csdn.net/stewen_001/article/details/19553173
配置好之后,我们就可以在编译器下运行代码,对数据库的表进行增删查改等操作。参考下列代码
package com.sql; //自己定义的包名
import java.sql.*;
public class test { //自己定义的class类
public static void main(String[] args) {
<span style="white-space:pre"></span>String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";<span style="white-space:pre"></span>String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=University";<span style="white-space:pre"></span>String userName="sa";<span style="white-space:pre"></span>String userPwd="yip123";
try{Class.forName(driverName);<span style="white-space:pre"></span>Connection conn = DriverManager.getConnection(dbURL,userName,userPwd);<span style="white-space:pre"></span>System.out.println("连接数据库成功");<span style="white-space:pre"></span>Statement stmt = conn.createStatement();//创建SQL命令对象
//增System.out.println("开始增加记录(在University数据库的student表增加一条记录)");<span style="white-space:pre"></span>PreparedStatement add = conn.prepareStatement("insert into student (ID,name,dept_name,tot_cred) values ('12334','yip','Biology','66')");<span style="white-space:pre"></span>add.executeUpdate(); <span style="white-space:pre"></span>System.out.println("插入成功" + '\n');
//删System.out.println("开始删除记录(在University数据库的teaches表删除一条记录)");PreparedStatement delete = conn.prepareStatement("delete from teaches where (ID = 222222)");delete.executeUpdate(); System.out.println("删除成功" + '\n');//查System.out.println("开始查询、读取数据");ResultSet result=stmt.executeQuery("SELECT * FROM classroom");//返回SQL语句查询结果集(集合) while(result.next()) { //输出每个字段 System.out.println(result.getString("building")+"\t"+result.getString("room_number")+"\t"+result.getString("capacity")); } System.out.println("查询、读取完毕" + '\n'<span style="font-family: Arial, Helvetica, sans-serif;">); </span>
//改System.out.println("开始更新记录(在University数据库的student表中更新一条记录)");PreparedStatement update = conn.prepareStatement("update student set dept_name='Physics' where name='yip' ");update.executeUpdate(); System.out.println("更新成功" + '\n');stmt.close();//关闭命令对象连接 conn.close();//关闭数据库连接 }catch(Exception e){e.printStackTrace();System.out.print("连接失败");} } }