日期:2014-05-16  浏览次数:20530 次

简单的数据库链接
import java.sql.*;
// 创建数据库链接
public class MySqlConnection {
public static Connection getConnection() {
Connection con = null;

try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://192.168.0.226:3306/ernschool";
con = DriverManager.getConnection(url, "root", "root");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}


public String loginValidate(String name, String passwd) {

conn = MySqlConnection.getConnection();

try {
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
String sql = "select state from r_sysOper where operName=? and operPass= ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, passwd);
ResultSet rs = pstmt.executeQuery();

String ustate = null;
while (rs.next()) {
ustate = rs.getString("state");
return ustate;
}
rs.close();
conn.close();
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}

return null;
}



package com.sdzn.dao;

import java.sql.*;
import java.util.List;

public class WordOper {

public void savaWord(String content){
Connection conn = MySqlConnection.getConnection();
try {
PreparedStatement pstat = conn.prepareStatement("insert into word(content)values(?)");
pstat.setString(1, content);

pstat.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}

public ResultSet queryWord(){
Connection conn = MySqlConnection.getConnection();
try {
Statement stat = conn.createStatement();
ResultSet result = stat.executeQuery("select * from word");
return result;
} catch (SQLException e) {
e.printStackTrace();
return null;
}

}

public void deleteWord(int id){
Connection conn = MySqlConnection.getConnection();

try {
PreparedStatement pstat = conn.prepareStatement("delete from word where id=?");
pstat.setInt(1, 1);
pstat.execute();

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

public void updateWord(String content,int id){
Connection conn = MySqlConnection.getConnection();
try {
Statement stat = conn.createStatement();
stat.execute("update word set content='"+content+"' where id="+id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static void main(String args[]){
WordOper wordOper = new WordOper();
wordOper.savaWord("contes2333444");

wordOper.deleteWord(1);
wordOper.updateWord("1111111111444444444888", 2);

ResultSet result = wordOper.queryWord();
try {
while(result.next()){
System.out.println(result.getString("content"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}