使用java链接本地的数据库并插入数据
使用类方法安静的关闭数据流
另外如果仅仅用了try/catch语句,这里是有很大的隐患的。在程序创建连接之后,如果不进行关闭,会消耗更多的资源。创建连接之后的代码挂掉了,后面的try/catch很难保证代码被执行,所以应该在finally里面进行对资源的关闭
package abc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
//import java.sql.PreparedStatement;
import java.sql.SQLException;
public class main
{
public static void main(String[] args)
{
try
{
/*
*链接数据库
*/
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
// TODO 自动生成的 catch 块
System.out.println("mysql的 jdbc的驱动加载失败"+e.getMessage());
return ;
}//加载了JDBC的驱动
//检查异常,非检查异常
Connection conn= null;
PreparedStatement stmt =null;
//DriverManager
try
{
conn=DriverManager.getConnection("jdbc:mysql://localhost/study1?seUnicode=true&characterEncoding=UTF-8","root","root");
System.out.println(conn.getClass());
//prepareStatement 准备执行,返回他的对象
stmt=conn.prepareStatement("insert into t_person(Name,Age,Gender) value('傻逼',19,1)");
// stmt.executeUpdate();
int i=stmt.executeUpdate();
System.out.println("执行成功 影响了"+i+"条数据");
/*
* 资源并没有被回收
* 一直连着不放 会一直链接 被卡死
*
*/
}
catch (SQLException e)
{
// TODO 自动生成的 catch 块
System.out.println("链接mysql失败"+e.getMessage());
}
// System.out.println("链接成功");
finally
{
JDBCGB.closeQuiety(conn);
JDBCGB.closeQuiety(stmt);
}
/*
if(stmt!=null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
//System.out.println("无法关闭数据流");
}
}
if(conn!=null)
{
try
{
conn.close();
}
catch (SQLException e)
{
// TODO 自动生成的 catch 块
// e.printStackTrace();
}
}*/
}
}
package abc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
//安静的关闭
public class JDBCGB
{
public static void closeQuiety(PreparedStatement stmt)
{
if(stmt!=null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
//System.out.println("无法关闭数据流");
}
}
}
public static void closeQuiety(Connection conn)
{
if(conn!=null)
{
try
{
conn.close();
}
catch (SQLException e)
{
// TODO 自动生成的 catch 块
// e.printStackTrace();
}
}
}
}