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();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值