Estou aprendendo Java e Banco de Dados recentemente. Lembro -me do sistema de gerenciamento de estudantes que escrevi antes, que foi baixado da Internet e era superficial. Eu não tinha nada a fazer, então escrevi um, mas as funções não implementaram muitas funções.
Linguagem de desenvolvimento: Java; Ambiente de Desenvolvimento: MySQL, Java; Ferramentas de desenvolvimento: Eclipse
Para desenvolver este caso, você deve primeiro ter o ambiente de desenvolvimento Java e o MySQL no computador, o ambiente de desenvolvimento Java e a construção do MySQL, para não descrevê -lo mais. Se precisar, entre em contato comigo com as seguintes informações de contato: [email protected]
O sistema é relativamente simples desta vez: existe apenas uma tabela no banco de dados: STU; Função: pode adicionar, excluir e modificar os alunos.
Etapas de desenvolvimento:
1. Crie tabelas no banco de dados:
Crie a tabela Stu (string stuid, string atluname, String String, Stuage Int, Stujg String, Studep Sring);
2.Java Código consiste principalmente em quatro classes:
Test3 contém a função principal; O stumodel é usado para atualizar e renderizar o banco de dados; Stuadddiag é usado para adicionar funções do leitor; Stuupdiag é usado para modificar as informações do aluno. O código específico é o seguinte:
Test3.java:
importar javax.swing.*; importar java.util.*; importar java.awt. java.sql.statement; public class Test3 estende JFRame implementa ActionListener {// Definir alguns controles jpanel JP1, JP2; Jlabel JL1, JL2; JButton JB1, JB2, JB3, JB4; Jtable jt; JScrollPane JSP; JTEXTFIELD JTF; Stumodel SM; // Defina a declaração variável stat = null; Preparado PS; Conexão ct = null; ResultSet rs = null; public static void main (string [] args) {test3 test3 = new test3 (); } // construtor public test3 () {jp1 = new jpanel (); JTF = novo JTextfield (10); jb1 = novo jbutton ("Query"); jb1.addactionListener (isto); jl1 = new jlabel ("Por favor, digite o nome:"); jp1.add (JL1); jp1.add (JTF); jp1.add (JB1); jb2 = novo jbutton ("add"); jb2.addactionListener (isto); jb3 = novo jbutton ("modify"); jb3.addactionListener (isto); jb4 = novo jbutton ("delete"); jb4.addactionListener (isto); jp2 = new jpanel (); JP2.Add (JB2); JP2.Add (JB3); JP2.Add (JB4); // crie modelo objeto sm = new stumodel (); // inicialize jt = novo jtable (sm); JSP = novo JScrollPane (JT); // coloca o jsp no jframe this.add (jsp); this.add (JP1, "Norte"); this.add (JP2, "Sul"); this.SetSize (600, 400); //this.setLocation(300, 200); this.setDefaultCloseoperation (exit_on_close); this.setVisible (true); } public void actionPerformed (ActionEvent arg0) {// Determine qual botão é clicado se (arg0.getSource () == jb1) {System.out.println ("O usuário deseja ser consultado ..."); // Como os dados da tabela são encapsulados em stumodel, é mais fácil concluir o nome da string de consulta = this.jtf.getText (). TRIM (); // Escreva uma instrução sql string sql = "selecione * de stu where atuname = '"+name+"'"; // Crie uma classe de modelo de dados e atualize SM = new Stumodel (SQL); // Atualize jtable jt.setModel (SM); } // 1. Retire a interface add else if (arg0.getSource () == jb2) {System.out.println ("add ..."); Stuadddiag sa = new Stuadddiag (isto, "Adicionar aluno", verdadeiro); // Obtenha novo modelo de dados novamente, SM = new Stumodel (); jt.setModel (SM); } else if (arg0.getSource () == jb4) {// 2. Exclua o registro // 1. Obtenha o ID do aluno int ROWNUM = this.jt.getSelectedRow (); // getSelectedRow retornará à linha no ponto do usuário // Se o usuário não tiver uma linha selecionada, retorne -1 se (ROWNUM == -1) {// Prompt JoptionPane.ShowMessagedialog ("Selecione uma linha"); retornar ; } // Obtenha a string de identificação acadêmica STUID = (String) Sm.getValuEat (ROWNUM, 0); System.out.println ("id:"+stuid); // Conecte o banco de dados e preencha a tarefa de exclusão, tente {// 1. Carregue a classe Driver.ForName ("com.mysql.jdbc.driver"); // 2. Conecte -se ao banco de dados String url = "jdbc: mysql: // localhost: 3306/spdb1"; String user = "root"; String passwd = "lfdy"; CT = DriverManager.getConnection (URL, Usuário, Passwd); System.out.println ("conexão bem -sucedida"); ps = ct.Preparestatement ("Exclua de Stu onde Stuid =?"); ps.SetString (1, Stuid); ps.execUteUpdate (); } catch (Exceção e) {e.printStackTrace (); } finalmente {tente {if (rs! = null) {rs.close (); rs = nulo; } if (ps! = null) {ps.close (); ps = null; } if (ct! = null) {ct.close (); CT = nulo; }} catch (Exceção e) {e.printStackTrace (); }} sm = new Stumodel (); // Atualize jtable jt.setModel (SM); } else if (arg0.getSource () == jb3) {System.out.println ("11111"); // 3. Os usuários desejam modificar int rownum = this.jt.getSelectedRow (); if (rownum == -1) {// Prompt joptionpane.showMessagedialog (isto, "Selecione uma linha"); retornar ; } // Mostrar diálogo System.out.println ("12435"); Stuupdiag su = new Stuupdiag (isto, "modificar acadêmico", verdadeiro, SM, Rownum); sm = novo stumodel (); jt.setModel (SM); }}}Stumodel.java:
/** Este é o meu modelo de tabela STU* Você pode encapsular todas as operações nas tabelas de estudantes nesta classe*/pacote com.test2; importar java.sql.Connection; importar java.sql.driverManager; importar java.sql.resultset; java.ql.statement; importação; Stumodel estende abstrataTableModel {// rowdata armazena dados de linha, colunmNames armazena nomes de colunas vector rowdata, colunnNames; // Defina o status de instrução variável que se conecta ao banco de dados = null; Conexão ct = null; ResultSet rs = null; // inicialize public void init (string sql) {if (sql.equals ("")) {sql = "selecione * de stu"; } // intermediário // Defina o nome da coluna columnNames = new Vector (); columnNames.add ("Número da escola"); columnNames.add ("nome"); columnNames.add ("gênero"); columnNames.add ("Age"); columnNames.add ("nome"); columnNames.add ("nome"); columnNames.add ("nome"); columnNames.add ("seita"); // rowdata armazena várias linhas rowdata = new vetor (); tente {// 1. Carregue a classe do driver.ForName ("com.mysql.jdbc.driver"); System.out.println ("Carregando com sucesso"); // 2. Conecte -se ao banco de dados // defina várias constantes string url = "jdbc: mysql: // localhost: 3306/spdb1"; String user = "root"; String passwd = "lfdy"; CT = DriverManager.getConnection (URL, Usuário, Passwd); stat = ct.createstatement (); // Crie objeto estatal rs = stat.executeQuery (sql); // resultado de consulta while (rs.Next ()) {vetor hang = new Vector (); hang.add (rs.getString (1)); hang.add (rs.getString (2)); hang.add (rs.getString (3)); hang.add (rs.getInt (4)); hang.add (rs.getString (5)); hang.add (rs.getString (6)); // Adicionar a rowdata.add (hang); }} catch (Exceção e) {e.printStackTrace (); } finalmente {tente {if (rs! = null) {rs.close (); rs = nulo; } if (stat! = null) {stat.close (); stat = null; } if (ct! = null) {ct.close (); CT = nulo; }} catch (Exceção e) {e.printStackTrace (); }}} // Adicione a função do aluno public void addstu (string sql) {// termina a tarefa de adição com base na instrução SQL inserida pelo usuário} // O segundo construtor obtém o modelo de dados através da instrução SQL aprovada Stumodel (string sql) {this.init (sql); } // construtor, usado para inicializar meu modelo de dados (tabela) public stumodel () {this.init (""); } // Obtenha quantas linhas existem int getRowCount () {// TODO Método Gerado automático Retornar tê-lo.rowdata.size (); } // Obtenha quantas colunas existem int getColumnCount () {// TODO Method Auto-Gerated Stub Return this.columnNames.size (); } // Obtenha dados de uma linha e uma coluna Public Object getValueat (int linha, int coluna) {// TODO Method Method Stub Return ((vetor) (this.rowdata.get (linha))). Get (coluna); } // Obtenha o nome do atributo public string getColumnName (int column) {// TODO Method Auto-Generated Stub Return (String) this.columnNames.get (colun); }}Stuadddiag.java:
pacote com.test2; importar javax.swing.jdialog; importar javax.swing. Java.SQL.*; Classe pública Stuadddiag estende JDialog implementa ActionListener {// Defina o componente de swing que eu preciso de Jlabel JL1, JL2, JL3, JL4, JL5, JL6; JTEXTFIELD JF1, JF2, JF3, JF4, JF5, JF6; JPanel JP1, JP2, JP3; JButton JB1, JB2; // Janela pai do proprietário Ghostwriter, o título é o nome da janela, o Modal especifica que é uma janela padrão () ou uma janela não moda public stuadddiag (proprietário do quadro, título da string, modal booleano) {// chamando a classe pai Método Super (proprietário, título, modal); JL1 = novo Jlabel ("Número do Estudo"); jl2 = new jlabel ("nome"); jl3 = novo Jlabel ("gênero"); JL4 = novo Jlabel ("Age"); jl5 = new jlabel ("home"); jl6 = new jlabel ("seita"); jf1 = novo JTextfield (10); jf2 = novo JTextfield (10); jf3 = novo JTextfield (10); jf4 = novo JTextfield (10); jf5 = novo JTextfield (10); jf6 = novo JTextfield (10); jb1 = novo jbutton ("add"); jb1.addactionListener (isto); jb2 = novo jbutton ("cancel"); jp1 = new jpanel (); jp2 = new jpanel (); jp3 = new jpanel (); // defina o layout jp1.setLayout (novo gridlayout (6,1)); JP2.SetLayout (New GridLayout (6,1)); jp3.add (JB1); jp3.add (JB2); jp1.add (JL1); jp1.add (JL2); jp1.add (JL3); jp1.add (JL4); jp1.add (JL5); jp1.add (JL6); JP2.Add (JF1); JP2.Add (JF2); JP2.Add (JF3); JP2.Add (JF4); JP2.Add (JF5); JP2.Add (JF6); this.add (jp1, borderlayout.west); this.add (jp2, borderlayout.center); this.add (jp3, borderlayout.south); this.SetSize (300.200); this.setVisible (true); } @Override public void ActionPerformed (ActionEvent E) {// TODO Método Gerado automaticamente Stub if (e.getSource () == jb1) {conexão ct = null; Preparado PSTMT de estatuto preparado = null; ResultSet rs = null; tente {// 1. Carregue a classe do driver.ForName ("com.mysql.jdbc.driver"); System.out.println ("carregado com sucesso"); // 2. Conecte -se ao banco de dados // defina várias constantes string url = "jdbc: mysql: // localhost: 3306/spdb1"; String user = "root"; String passwd = "lfdy"; CT = DriverManager.getConnection (URL, Usuário, Passwd); // Declaração compilada Objeto String strsql = "Insira nos valores STU (?,?, ,?,? ,?)"; pstmt = ct.preparestatement (strSQL); // Atribua o objeto Pstmt.SetString (1, jf1.getText ()); pstmt.SetString (2, jf2.getText ()); Pstmt.SetString (3, JF3.getText ()); pstmt.SetString (4, jf4.getText ()); pstmt.SetString (5, jf5.getText ()); pstmt.SetString (6, jf6.getText ()); pstmt.executeUpdate (); this.dispose (); // Fechar a caixa de diálogo do aluno} Catch (exceção arg1) {arg1.printStackTrace (); } finalmente {tente {if (rs! = null) {rs.close (); rs = nulo; } if (pstmt! = null) {pstmt.close (); pstmt = null; } if (ct! = null) {ct.close (); CT = nulo; }} catch (exceção arg2) {arg2.printStackTrace (); }}}}}}Stuupdiag.java:
pacote com.test2;/** Modifique os alunos*/importe javax.swing.jdialog; importar javax.swing.*; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; import java.sql.statement; importDRA.SQL.Connection; Import; Java.SQL.ResultSet; importar java.SQL.SQL. JTEXTFIELD JF1, JF2, JF3, JF4, JF5, JF6; JPanel JP1, JP2, JP3; JButton JB1, JB2; // Proprietário Pen-in-the-Parent Janela, o título é o nome da janela, o Modal especifica que é uma janela de modo () ou uma janela não moda pública Stuupdiag (proprietário do quadro, título da string, modal booleano, stumodel sm, int rownum) {// chamando a classe pai Super (proprietário, título, modal); JL1 = novo Jlabel ("Número do aluno"); jl2 = new jlabel ("nome"); jl3 = novo Jlabel ("gênero"); JL4 = novo Jlabel ("Age"); jl5 = new jlabel ("nome"); jl6 = new jlabel ("seção"); jf1 = novo JTextfield (10); jf1.settext ((sm.getValuEat (rownum, 0)). tostring ()); jf2 = novo JTextfield (10); jf2.Settext ((String) sm.getValuEat (rownum, 1)); jf3 = novo JTextfield (10); jf3.Settext (sm.getValueat (rownum, 2) .toString ()); jf4 = novo JTextfield (10); jf4.Settext ((Sm.getValueat (ROWNUM, 3)). ToString ()); jf5 = novo JTextfield (10); jf5.Settext ((String) sm.getValuEat (rownum, 4)); jf6 = novo JTextfield (10); jf6.settext (((string) sm.getValuEat (rownum, 5)); jb1 = novo jbutton ("modify"); jb1.addactionListener (isto); jb2 = novo jbutton ("cancel"); jp1 = new jpanel (); jp2 = new jpanel (); jp3 = new jpanel (); // defina o layout jp1.setLayout (novo gridlayout (6,1)); JP2.SetLayout (New GridLayout (6,1)); jp3.add (JB1); jp3.add (JB2); jp1.add (JL1); jp1.add (JL2); jp1.add (JL3); jp1.add (JL4); jp1.add (JL5); jp1.add (JL6); JP2.Add (JF1); JP2.Add (JF2); JP2.Add (JF3); JP2.Add (JF4); JP2.Add (JF5); JP2.Add (JF6); this.add (jp1, borderlayout.west); this.add (jp2, borderlayout.center); this.add (jp3, borderlayout.south); this.SetSize (300.200); this.setVisible (true); } @Override public void ActionPerformed (ActionEvent E) {// TODO Método Gerado automaticamente Stub if (e.getSource () == jb1) {conexão ct = null; Preparado PSTMT de estatuto preparado = null; ResultSet rs = null; tente {// 1. Carregue a classe do driver.ForName ("com.mysql.jdbc.driver"); System.out.println ("carregado com sucesso"); // 2. Conecte -se ao banco de dados // defina várias constantes string url = "jdbc: mysql: // localhost: 3306/spdb1"; String user = "root"; String passwd = "lfdy"; CT = DriverManager.getConnection (URL, Usuário, Passwd); // Declaração compilada Objeto String strsql = "Insira nos valores STU (?,?, ,?,? ,?)"; pstmt = ct.preparestatement (strSQL); // Atribua o objeto Pstmt.SetString (1, jf1.getText ()); pstmt.SetString (2, jf2.getText ()); Pstmt.SetString (3, JF3.getText ()); pstmt.SetString (4, jf4.getText ()); pstmt.SetString (5, jf5.getText ()); pstmt.SetString (6, jf6.getText ()); pstmt.executeUpdate (); this.dispose (); // Fechar a caixa de diálogo do aluno} Catch (exceção arg1) {arg1.printStackTrace (); } finalmente {tente {if (rs! = null) {rs.close (); rs = nulo; } if (pstmt! = null) {pstmt.close (); pstmt = null; } if (ct! = null) {ct.close (); CT = nulo; }} catch (exceção arg2) {arg2.printStackTrace (); }}}}}}Resultados de desenvolvimento e teste:
1. Interface principal do sistema:
2. Consulta pelo nome:
3. Selecione uma linha e exclua:
4. Selecione uma linha para modificar:
5. Clique no botão Adicionar para adicionar:
Este sistema continuará sendo aprimorado. Se você tiver alguma dúvida ou trocas técnicas, entre em contato comigo: [email protected]
Para obter mais informações sobre o sistema de gerenciamento, clique em "Tópico especial do sistema de gerenciamento" para aprender
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.