您的位置:首页 > 数据库 > MySQL

JDBC连接Mysql数据库

2015-11-27 09:47 471 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: