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

连接mysql数据库相关语句

2011-07-28 11:29 246 查看
package com.test.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;
public class DBConnect {
static Connection conn = null;
static Statement st = null;
static ResultSet rs = null;
public static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
Logger.getLogger(e.getMessage());
}
try {
conn = DriverManager.getConnection(
"Jdbc:mysql://localhost:3306/test", "root", "root");
} catch (SQLException e) {
e.getMessage();
if (conn != null) {
conn.close();
}
}
return conn;
}
public static int getInsert(int sid, String sname, String sex)
throws SQLException {
conn = getConnection();
int i = 0;
String sql = "insert into student values("+sid+",'" + sname + "','" + sex
+ "')";
/*
* 这里要注意细节上的错误,如果把sid写成字符串,在插入数据的时候会出现异常。
而且在这个地方通常网上说的那种情况“数据库里序号没有设置成自增”在这里不适用。
*/
try {
st = conn.createStatement();
i = st.executeUpdate(sql);
} catch (Exception e) {
if (conn != null)
conn.close();
e.printStackTrace();
}
return i;
}
public static String getSelect() throws SQLException {
conn = getConnection();
String sql = "select * from student";
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
rs.getInt("sid");
rs.getString("sname");
rs.getString("sex");
System.out.println(rs.getInt("sid") + ","
+ rs.getString("sname") + "," + rs.getString("sex"));
}
} catch (SQLException e) {
rs.close();
if (conn != null)
conn.close();
e.printStackTrace();
}
return null;
}
public static int getUpdate(int sid, String sna, String se)
throws SQLException {
conn = getConnection();
int i = 0;
String sql = "update student set sname='" + sna + "',sex='" + se + "'";
sql = sql + " where sid=" + sid;
try {
st = conn.createStatement();
i = st.executeUpdate(sql);
} catch (Exception e) {
if (conn != null)
conn.close();
e.printStackTrace();
}
return i;
}
public static void getDelete(int sid) throws Exception {
conn = getConnection();
String sql = "delete from student where sid=" + sid;
conn.createStatement().execute(sql);
if (conn != null)
conn.close();
}
public static void main(String args[]) throws Exception {
DBConnect.getConnection();
// DBConnect.getInsert(6, "werrr", "m");
DBConnect.getUpdate(1, "1", "uii");
DBConnect.getSelect();
DBConnect.getDelete(0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: