现在的位置: 首页 > 综合 > 正文

连接mysql数据库相关语句

2013年08月18日 ⁄ 综合 ⁄ 共 2302字 ⁄ 字号 评论关闭
 

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);
 }

}

抱歉!评论已关闭.