1.Java連接MySQL數(shù)據(jù)庫
創(chuàng)新互聯(lián)建站服務(wù)項(xiàng)目包括杜集網(wǎng)站建設(shè)、杜集網(wǎng)站制作、杜集網(wǎng)頁制作以及杜集網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,杜集網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到杜集省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
Java連接MySql需要下載JDBC驅(qū)動MySQL-connector-java-5.0.5.zip(舉例,現(xiàn)有新版本)。然后將其解壓縮到任一目錄。我是解壓到D盤,然后將其目錄下的MySQL-connector-java-5.0.5-bin.jar加到classpath里,具體如下:
“我的電腦”- “屬性” - “高級” - “環(huán)境變量”,在系統(tǒng)變量那里編輯classpath,將D:\MySQL-connector-java-5.0.5\MySQL-connector-java-5.0.5-bin.jar加到最后,在加這個字符串前要加“;”,以與前一個classpath區(qū)分開。然后確定。
package hqs;
import java.sql.*;
public class DataBasePractice {
public static void main(String[] args) {
//聲明Connection對象
Connection con;
//驅(qū)動程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要訪問的數(shù)據(jù)庫名mydata
String url = "jdbc:mysql://localhost:3306/mydata";
//MySQL配置時的用戶名
String user = "root";
//MySQL配置時的密碼
String password = "root";
//遍歷查詢結(jié)果集
try {
//加載驅(qū)動程序
Class.forName(driver);
//1.getConnection()方法,連接MySQL數(shù)據(jù)庫??!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.創(chuàng)建statement類對象,用來執(zhí)行SQL語句??!
Statement statement = con.createStatement();
//要執(zhí)行的SQL語句
String sql = "select * from student";
//3.ResultSet類,用來存放獲取的結(jié)果集??!
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("執(zhí)行結(jié)果如下所示:");
System.out.println("-----------------");
System.out.println(" 學(xué)號" + "\t" + " 姓名");
System.out.println("-----------------");
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數(shù)據(jù)
name = rs.getString("stuname");
//獲取stuid這列數(shù)據(jù)
id = rs.getString("stuid");
//首先使用ISO-8859-1字符集將name解碼為字節(jié)序列并將結(jié)果存儲新的字節(jié)數(shù)組中。
//然后使用GB2312字符集解碼指定的字節(jié)數(shù)組。
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
//輸出結(jié)果
System.out.println(id + "\t" + name);
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//數(shù)據(jù)庫驅(qū)動類異常處理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//數(shù)據(jù)庫連接失敗異常處理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("數(shù)據(jù)庫數(shù)據(jù)成功獲?。?!");
}
}
}
2.添加、修改、刪除操作
在上面while代碼段后面添加以下代碼段:String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數(shù)據(jù)
name = rs.getString("stuname");
//獲取stuid這列數(shù)據(jù)
id = rs.getString("stuid");
//首先使用ISO-8859-1字符集將name解碼為字節(jié)序列并將結(jié)果存儲新的字節(jié)數(shù)組中。
//然后使用GB2312字符集解碼指定的字節(jié)數(shù)組。
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
//輸出結(jié)果
System.out.println(id + "\t" + name);
}
PreparedStatement psql;
ResultSet res;
//預(yù)處理添加數(shù)據(jù),其中有兩個參數(shù)--“?”
psql = con.prepareStatement("insert into student values(?,?)");
psql.setInt(1, 8); //設(shè)置參數(shù)1,創(chuàng)建id為5的數(shù)據(jù)
psql.setString(2, "xiaogang"); //設(shè)置參數(shù)2,name 為小明
psql.executeUpdate(); //執(zhí)行更新
//預(yù)處理更新(修改)數(shù)據(jù)
psql = con.prepareStatement("update student set stuname = ? where stuid = ?");
psql.setString(1,"xiaowang"); //設(shè)置參數(shù)1,將name改為王五
psql.setInt(2,10); //設(shè)置參數(shù)2,將id為2的數(shù)據(jù)做修改
psql.executeUpdate();
//預(yù)處理刪除數(shù)據(jù)
psql = con.prepareStatement("delete from student where stuid = ?");
psql.setInt(1, 5);
psql.executeUpdate();
//查詢修改數(shù)據(jù)后student表中的數(shù)據(jù)
psql = con.prepareStatement("select*from student");
res = psql.executeQuery(); //執(zhí)行預(yù)處理sql語句
System.out.println("執(zhí)行增加、修改、刪除后的數(shù)據(jù)");
while(res.next()){
name = res.getString("stuname");
id = res.getString("stuid");
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
System.out.println(id + "\t" + name);
}
res.close();
psql.close();
該代碼段使用到了預(yù)處理語句:con.prepareStatement(String sql);
這樣生成數(shù)據(jù)庫底層的內(nèi)部命令,并將該命令封裝在preparedStatement對象中,可以減輕數(shù)據(jù)庫負(fù)擔(dān),提高訪問數(shù)據(jù)庫速度。 運(yùn)行結(jié)果:
做這個題庫系統(tǒng)需要按照mvc設(shè)計一下, 最近我也實(shí)現(xiàn)一個類似的, 下面說下我的設(shè)計
數(shù)據(jù)庫mysql+開發(fā)環(huán)境eclipse+jdk1.8, 然后基于一個整合框架把項(xiàng)目搭建起來
設(shè)計基礎(chǔ)試題表, 這個主要有類型難度等等
設(shè)計試卷表, 試卷表由create的時候根據(jù)輸入的規(guī)則自動根據(jù)上面的基礎(chǔ)題庫表組裝而成
剩下的用戶管理, 導(dǎo)出就比較容易了, 導(dǎo)出可以用poi導(dǎo)出成word
//主類EnglishTest——
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EnglishTest extends JFrame
{
TestArea testPanel=null;
Container con=null;
public EnglishTest()
{
super("模擬考試");
testPanel=new TestArea();
con=getContentPane();
con.add(testPanel,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
setVisible(true);
setBounds(60,40,660,460);
con.validate();
validate();
}
public static void main(String args[])
{
new EnglishTest();
}
}
//讀取試題 ReadTestquestion
import java.io.*;
import java.util.*;
public class ReadTestquestion
{ String filename="",
correctAnswer="",
testContent="" ,
selection="" ;
int score=0;
long time=0;
boolean 完成考試=false;
File f=null;
FileReader in=null;
BufferedReader 讀取=null;
public void setFilename(String name)
{ filename=name;
score=0;
selection="";
try {
if(in!=null讀取!=null)
{
in.close();
讀取.close();
}
f=new File(filename);
in=new FileReader(f);
讀取=new BufferedReader(in);
correctAnswer=(讀取.readLine()).trim();
String temp=(讀取.readLine()).trim() ;
StringTokenizer token=new StringTokenizer(temp,":");
int hour=Integer.parseInt(token.nextToken()) ;
int minute=Integer.parseInt(token.nextToken());
int second=Integer.parseInt(token.nextToken());
time=1000*(second+minute*60+hour*60*60);
}
catch(Exception e)
{
testContent="沒有選擇試題";
}
}
public String getFilename()
{
return filename;
}
public long getTime()
{
return time;
}
public void set完成考試(boolean b)
{
完成考試=b;
}
public boolean get完成考試()
{
return 完成考試;
}
public String getTestContent()
{ try {
String s=null;
StringBuffer temp=new StringBuffer();
if(讀取!=null)
{
while((s=讀取.readLine())!=null)
{
if(s.startsWith("**"))
break;
temp.append("\n"+s);
if(s.startsWith("endend"))
{
in.close();
讀取.close();
完成考試=true;
}
}
testContent=new String(temp);
}
else
{
testContent=new String("沒有選擇試題");
}
}
catch(Exception e)
{
testContent="試題內(nèi)容為空,考試結(jié)束!!";
}
return testContent;
}
public void setSelection(String s)
{
selection=selection+s;
}
public int getScore()
{ score=0;
int length1=selection.length();
int length2=correctAnswer.length();
int min=Math.min(length1,length2);
for(int i=0;imin;i++)
{ try{
if(selection.charAt(i)==correctAnswer.charAt(i))
score++;
}
catch(StringIndexOutOfBoundsException e)
{
i=0;
}
}
return score;
}20:10 03-8-31
public String getMessages()
{
int length1=selection.length();
int length2=correctAnswer.length();
int length=Math.min(length1,length2);
String message="正確答案:"+correctAnswer.substring(0,length)+"\n"+
"你的回答:"+selection+"\n";
return message;
}
}
//考試區(qū)域TestArea
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class FileName implements FilenameFilter
{
String str=null;
FileName (String s)
{
str="."+s;
}
public boolean accept(File dir,String name)
{
return name.endsWith(str);
}
}
public class TestArea extends JPanel implements ActionListener,ItemListener,Runnable
{
Choice list=null;
JTextArea 試題顯示區(qū)=null,消息區(qū)=null;
JCheckBox box[];
JButton 提交該題答案,讀取下一題,查看分?jǐn)?shù);
ReadTestquestion 讀取試題=null;
JLabel welcomeLabel=null;
Thread countTime=null;
long time=0;
JTextField timeShow=null;
boolean 是否關(guān)閉計時器=false,
是否暫停計時=false;
JButton 暫?;蚶^續(xù)計時=null;
public TestArea()
{
list= new Choice();
String 當(dāng)前目錄=System.getProperty("user.dir");
File dir=new File(當(dāng)前目錄);
FileName fileTxt=new FileName("txt");
String fileName[]=dir.list(fileTxt);
for(int i=0;ifileName.length;i++)
{
list.add(fileName[i]);
}
試題顯示區(qū)=new JTextArea(15,12);
試題顯示區(qū).setLineWrap(true);
試題顯示區(qū).setWrapStyleWord(true);
試題顯示區(qū).setFont(new Font("TimesRoman",Font.PLAIN,14));
試題顯示區(qū).setForeground(Color.blue);
消息區(qū)=new JTextArea(8,8);
消息區(qū).setForeground(Color.blue);
消息區(qū).setLineWrap(true);
消息區(qū).setWrapStyleWord(true);
countTime=new Thread(this);
String s[]={"A","B","C","D"};
box=new JCheckBox[4];
for(int i=0;i4;i++)
{
box[i]=new JCheckBox(s[i]);
}
暫停或繼續(xù)計時=new JButton("暫停計時");
暫?;蚶^續(xù)計時.addActionListener(this);
提交該題答案=new JButton("提交該題答案");
讀取下一題=new JButton("讀取第一題");
讀取下一題.setForeground(Color.blue);
提交該題答案.setForeground(Color.blue);
查看分?jǐn)?shù)=new JButton("查看分?jǐn)?shù)");
查看分?jǐn)?shù).setForeground(Color.blue);
提交該題答案.setEnabled(false);
提交該題答案.addActionListener(this);
讀取下一題.addActionListener(this);
查看分?jǐn)?shù).addActionListener(this);
list.addItemListener(this);
讀取試題=new ReadTestquestion();
JPanel pAddbox=new JPanel();
for(int i=0;i4;i++)
{
pAddbox.add(box[i]);
}
Box boxH1=Box.createVerticalBox(),
boxH2=Box.createVerticalBox(),
baseBox=Box.createHorizontalBox();
boxH1.add(new JLabel("選擇試題文件"));
boxH1.add(list);
boxH1.add(new JScrollPane(消息區(qū)));
boxH1.add(查看分?jǐn)?shù));
timeShow=new JTextField(20);
timeShow.setHorizontalAlignment(SwingConstants.RIGHT);
timeShow.setEditable(false);
JPanel p1=new JPanel();
p1.add(new JLabel("剩余時間:"));
p1.add(timeShow);
p1.add(暫?;蚶^續(xù)計時);
boxH1.add(p1);
boxH2.add(new JLabel("試題內(nèi)容:"));
boxH2.add(new JScrollPane(試題顯示區(qū)));
JPanel p2=new JPanel();
p2.add(pAddbox);
p2.add(提交該題答案);
p2.add(讀取下一題);
boxH2.add(p2);
baseBox.add(boxH1);
baseBox.add(boxH2);
setLayout(new BorderLayout());
add(baseBox,BorderLayout.CENTER);
welcomeLabel=new JLabel("歡迎考試,提高英語水平",JLabel.CENTER);
welcomeLabel.setFont(new Font("隸書",Font.PLAIN,24));
welcomeLabel.setForeground(Color.blue);
add(welcomeLabel,BorderLayout.NORTH);
}
public void itemStateChanged(ItemEvent e)
{
timeShow.setText(null);
是否關(guān)閉計時器=false;
是否暫停計時=false;
暫?;蚶^續(xù)計時.setText("暫停計時");
String name=(String)list.getSelectedItem();
讀取試題.setFilename(name);
讀取試題.set完成考試(false);
time=讀取試題.getTime();
if(countTime.isAlive())
{
是否關(guān)閉計時器=true;
countTime.interrupt();
}
countTime=new Thread(this);
消息區(qū).setText(null);
試題顯示區(qū).setText(null);
讀取下一題.setText("讀取第一題");
提交該題答案.setEnabled(false);
讀取下一題.setEnabled(true);
welcomeLabel.setText("歡迎考試,你選擇的試題:"+讀取試題.getFilename());
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==讀取下一題)
{
讀取下一題.setText("讀取下一題");
提交該題答案.setEnabled(true);
String contentTest=讀取試題.getTestContent();
試題顯示區(qū).setText(contentTest);
消息區(qū).setText(null);
讀取下一題.setEnabled(false);
try {
countTime.start();
}
catch(Exception event)
{
}
}
if(e.getSource()==提交該題答案)
{
讀取下一題.setEnabled(true);
提交該題答案.setEnabled(false);
String answer="?";
for(int i=0;i4;i++)
{
if(box[i].isSelected())
{
answer=box[i].getText();
box[i].setSelected(false);
break;
}
}
讀取試題.setSelection(answer);
}
if(e.getSource()==查看分?jǐn)?shù))
{
int score=讀取試題.getScore();
String messages=讀取試題.getMessages();
消息區(qū).setText("分?jǐn)?shù):"+score+"\n"+messages);
}
if(e.getSource()==暫?;蚶^續(xù)計時)
{
if(是否暫停計時==false)
{
暫?;蚶^續(xù)計時.setText("繼續(xù)計時");
是否暫停計時=true;
}
else if(是否暫停計時==true)
{
暫?;蚶^續(xù)計時.setText("暫停計時");
是否暫停計時=false;
countTime.interrupt();
}
}
}
public synchronized void run()
{
while(true)
{
if(time=0)
{
是否關(guān)閉計時器=true;
countTime.interrupt();
提交該題答案.setEnabled(false);
讀取下一題.setEnabled(false);
timeShow.setText("用時盡,考試結(jié)束");
}
else if(讀取試題.get完成考試())
{
是否關(guān)閉計時器=true;
timeShow.setText("考試效果:分?jǐn)?shù)*剩余時間(秒)="+1.0*讀取試題.getScore()*(time/1000));
countTime.interrupt();
提交該題答案.setEnabled(false);
讀取下一題.setEnabled(false);
}
else if(time=1)
{
time=time-1000;
long leftTime=time/1000;
long leftHour=leftTime/3600;
long leftMinute=(leftTime-leftHour*3600)/60;
long leftSecond=leftTime%60;
timeShow.setText(""+leftHour+"小時"+leftMinute+"分"+leftSecond+"秒");
}
try
{
Thread.sleep(1000);
}
catch(InterruptedException ee)
{
if(是否關(guān)閉計時器==true)
return ;
}
while(是否暫停計時==true)
{
try
{
wait();
}
catch(InterruptedException ee)
{
if(是否暫停計時==false)
{
notifyAll();
}
}
}
}
}
}
當(dāng)前標(biāo)題:關(guān)于java考試模擬系統(tǒng)代碼的信息
URL標(biāo)題:http://muchs.cn/article34/doeicse.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計、搜索引擎優(yōu)化、營銷型網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)