java连接数据库程序

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class testJdbc {

public static void main(String[] args) {

        String driver = "com.mysql.jdbc.Driver";

        String dbName = "test";

        String passwrod = "dbproxy";

        String userName = "dbproxy";

        String url = "jdbc:mysql://10.10.00.00:3456/" + dbName;

//        if(args.length!=2){

  //      System.out.println("调用:java testJDBC ip:prot recordcut");

    //    }

    //    String args[0]= "10.10.56.83:";

     //   String url = "jdbc:mysql://"+args[0]+"/" + dbName;

     //   int cut = Integer.parseInt(args[1]);

        

        String sql = "SELECT * FROM t_app_info where status = 1;";

        try {

            Class.forName(driver);

            Connection conn = DriverManager.getConnection(url, userName,

                    passwrod);

            PreparedStatement ps = conn.prepareStatement(sql);

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {

                System.out.println("id : " + rs.getInt(1) + " appid : "

                        + rs.getString(2) + " name : " + rs.getString(3));

            }

            // 关闭记录集

            if (rs != null) {

                try {

                    rs.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

            // 关闭声明

            if (ps != null) {

                try {

                    ps.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

            // 关闭链接对象

            if (conn != null) {

                try {

                    conn.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

}

}

******************************************************************************************************************

在eclipse中引用mysql-connector-java-5.1.26-bin.jar

******************************************************************************************************************

猜你喜欢

转载自km-moon11.iteye.com/blog/1947617