`
myway84
  • 浏览: 204119 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
文章分类
社区版块
存档分类
最新评论

mysql 数据库连接

阅读更多
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;


public class MysqlConn {

private static DataSource ds=null;
private static Connection conn=null;

public static Connection getConn_jdbc()
{
String url="jdbc:mysql://localhost:3306/test";
String username="root";
String password="duanran";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("连接数据库异常");
}
return null;

}

public void CloseConn()
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("数据库关闭异常");
e.printStackTrace();
}
}

public static void main(String[] args)
{
  Connection conn;
  MysqlConn mc=new MysqlConn();
  conn=mc.getConn_jdbc();
 
  try {
Statement stmt=conn.createStatement();
String strSql="select * from test";
ResultSet rs=stmt.executeQuery(strSql);
while(rs.next())
{
System.out.println("name"+rs.getString("name"));
}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
mc.CloseConn();
}
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics