Java一个连接数据库的例子

      Java程序开发 2009-12-17 9:36:00

一个连接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();
            }
          
        }
    }
   
}

标签集:TAGS:
回复Comments() 点击Count()
喜欢就顶一下

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}