2009/12/17 | Java一个连接数据库的例子
类别(Java程序开发) | 评论(0) | 阅读(24) | 发表于 09:36

一个连接slq server的例子,需要的包还包括
package databasetest;

import java.sql.*;
public class Main {
   
    String  jdbc="com.microsoft.jdbc.sqlserver.SQLServerDriver";
    String  url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Student";
    String username="sa";
    String password="sa";
    /** Creates a new instance of Main */
    public Main() {
    }
   
    public ResultSet find(String sql) {
        ResultSet rs=null;
        try {
            Class.forName(jdbc).newInstance();
            Connection con= DriverManager.getConnection(url,username,password);
            Statement smt=con.createStatement();
            rs=smt.executeQuery(sql);
        } catch (Exception ex) {
           
        }

        return  rs;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String sql="select * from person";
        ResultSet rs=null;
        Main m=new Main();
        rs=m.find(sql);
        if(rs!=null)
        {
            try {
           
                while(rs.next())
                {
                 String name=rs.getString(1);
                 int age=rs.getInt(2);
                 String node=rs.getString(3);
                 String classid=rs.getString(4);
                 System.out.print("姓名:"+name);
                 System.out.print("年龄:"+age);
                 System.out.print("学号:"+node);
                 System.out.print("班级:"+classid);
                 System.out.print("\n");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
          
        }
    }
   
}

0

评论Comments