`
cdzm5211314
  • 浏览: 8157 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JDBC连接Mysql数据库

 
阅读更多
JDBC连接MySql数据库

第一个例子:

Java代码  收藏代码
public static void add() throws Exception 
    { 
        final String url = "jdbc:mysql://127.0.0.1:3306/test"; 
        final String user = "root"; 
        final String pwd = "1234"; 
        Connection cn = null; 
        Statement stm = null; 
        try 
        { 
            Class.forName("org.gjt.mm.mysql.Driver"); 
            cn = DriverManager.getConnection(url, user, pwd); 
            stm = cn.createStatement(); 
            final String sql = " insert into user values(9999999,'123','2008-01-01')"; 
            stm.execute(sql); 
        } 
        finally 
        { 
            stm.close(); 
            cn.close(); 
        } 
    } 


第二个例子:
Java代码  收藏代码
package dao; 
 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
 
/**
* @author zl JDBC连数据库的例子

*/ 
public class JDBC 

    public static Connection getConnection() 
    { 
        final String url = "jdbc:mysql://127.0.0.1:3306/test"; 
        final String sUsr = "root"; 
        final String sPwd = "1234"; 
        try 
        { 
            Class.forName("org.gjt.mm.mysql.Driver"); 
            return DriverManager.getConnection(url, sUsr, sPwd); 
        } 
        catch (final ClassNotFoundException e) 
        { 
            //TODO 找不到驱动 
        } 
        catch (final SQLException e) 
        { 
            //TODO 创建连接异常 
        } 
        return null; 
    } 
 
     
 
    public static void get() throws SQLException 
    { 
        final String sql = "SELECT id,name FROM user where id=?"; 
        PreparedStatement pstmt = null; 
        final Connection cn = getConnection(); 
        try 
        { 
            pstmt = cn.prepareStatement(sql); 
            pstmt.setInt(1, 468000); 
            final ResultSet rs = pstmt.executeQuery(); 
            while (rs.next()) 
            { 
                System.out.print(rs.getString("id")); 
                System.out.print(":"); 
                System.out.print(rs.getString("name") + "\r\n"); 
            } 
            rs.close(); 
            pstmt.close(); 
        } 
 
        finally 
        { 
            try 
            { 
                cn.close(); 
            } 
            catch (final SQLException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
    } 
 
    public static void main(final String[] args) throws Exception 
    { 
        get(); 
        //add(); 
    } 



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics