//代码示例:
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcSql {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//加载驱动 SqlServer2005
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//创建连接
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=test",
"sa", "admin");
//获取指令对象
st = conn.createStatement();
//发送指令,并返回结果
rs = st.executeQuery("select * from student");
//获取结果集
while(rs.next()){
System.out.println("id:"+rs.getInt(1));
System.out.println("userName:"+rs.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
//数据
create table student(
id int identity primary key,
userName nvarchar(10)
)
insert into student select'张三'
insert into student select'李四'
insert into student select'王五'
insert into student select'赵六'
insert into student values('林奇')