- package com.zuxia.jdbc;
- //1导入包
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.sql.ResultSet;
- @SuppressWarnings("unused")
- public class JdbcTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Connection con=null;
- String url="jdbc:sqlserver://localhost:1433;DataBaseName=Student";
- //构建查询语句
- String sql="select * from stuinfo";
- ResultSet rs=null;
- PreparedStatement psmt = null;
- try {
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//加载驱动
- con = DriverManager.getConnection(url,"sa","123456");//建立连接
- psmt = con.prepareStatement(sql);//预编译sql语句
- rs = psmt.executeQuery();//执行sql语句并保存结果到结果集
- while(rs.next()){
- System.out.println("编号:"+rs.getInt("id"));
- System.out.println("姓名:"+rs.getString("name"));
- System.out.println("性别:"+rs.getString(3));
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- finally{
- //关闭连接
- try {
- rs.close();
- psmt.close();
- con.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- insert();
- }
- public static void insert(){
- //声明连接对象
- Connection con=null;
- PreparedStatement ps=null;
- try{
- //加载驱动
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- //建立连接
- String url="jdbc:sqlserver://127.0.0.1:1433;DataBaseName=Student";
- con=DriverManager.getConnection(url, "sa", "123456");
- //构建sql语句
- String sql="insert into stuinfo values(?,?,?)";
- //预编译sql语句
- ps=con.prepareStatement(sql);
- //设置占位符
- ps.setString(1, "李磊");
- ps.setString(2, "女");
- ps.setString(3, "中国重庆");
- //执行sql语句
- if(0<ps.executeUpdate()){
- System.out.println("添加成功!");
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- finally{
- //关闭资源
- try{
- ps.close();
- con.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
貌似这个是比.net连接要老火的多哦