以编程方式启动Derby [英] Starting Derby Programmatically

查看:84
本文介绍了以编程方式启动Derby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码

DataBaseConnector.java

 import java.sql.*;
 import javax.swing.*;

    public class DataBaseConnector
    {
        private Connection con;

        public DataBaseConnector()
        {

        }

        private boolean createConnection()
        {
            try
            {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact;create=true","yohanrw","knight");
            }
            catch(Exception e)
            {      
                System.out.println("Error getConnection");
                e.printStackTrace();
                JOptionPane.showMessageDialog(null,e.getLocalizedMessage());
                return false;
            }
            return true;   
        }

        private void closeConnection()
        {
            try
            {
                con.close();
            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(null,e.getLocalizedMessage());
            }
        }


        public void insertData(int id, String firstName, String lastName)
        {
            createConnection();
            try
            {
                PreparedStatement ps = con.prepareStatement("insert into APP.FRIENDS values(?,?,?)");
                ps.setInt(1, id);
                ps.setString(2, firstName);
                ps.setString(3, lastName);

                int result = ps.executeUpdate();

                if(result>0)
                {
                    JOptionPane.showMessageDialog(null,"Data Inserted");
                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Something Happened");
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null,e.getLocalizedMessage());
            }
            finally
            {
                closeConnection();
            }
        }

        public void viewData()
        {
            createConnection();

            try
            {
                Statement st = con.createStatement();
                ResultSet rs = st.executeQuery("select * from APP.FRIENDS");

                StringBuffer sb = new StringBuffer("");

                while(rs.next())
                {
                    sb.append(rs.getInt(1)+"\n");
                    sb.append(rs.getString(2)+"\n");
                    sb.append(rs.getString(3)+"\n");


                }

                JOptionPane.showMessageDialog(null,sb);
            }
            catch(Exception e)
            {



            }
        }


    }

数据库用户界面

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class DatabaseUI extends JFrame
{
    private JLabel firstName, id, lastName;
    private JTextField idTxt, firstNameTxt, lastNameTxt;
    private JButton ok, view;

    public DatabaseUI()
    {
     firstName = new JLabel("First Name: ");
     lastName = new JLabel("Last Name: ");
     id = new JLabel("ID: ");

     firstNameTxt = new JTextField(10);
     lastNameTxt = new JTextField(10);
     idTxt = new JTextField(10);

     ok = new JButton("ADD");
     ok.addActionListener(new OKAction());
     view = new JButton("View");
     view.addActionListener(new ViewAction());

     JPanel centerPanel = new JPanel();
     centerPanel.setLayout(new GridLayout(4,2));
     centerPanel.add(id);
     centerPanel.add(idTxt);
     centerPanel.add(firstName);
     centerPanel.add(firstNameTxt);
     centerPanel.add(lastName);
     centerPanel.add(lastNameTxt);
     centerPanel.add(view);
     centerPanel.add(ok);

     getContentPane().add(centerPanel,"Center");


     this.pack();
     this.setVisible(true);
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }

    private class OKAction implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
            DataBaseConnector db = new DataBaseConnector();

            int id = Integer.parseInt(idTxt.getText());

            db.insertData(id, firstNameTxt.getText().trim(), lastNameTxt.getText().trim());
        }
    }

    private class ViewAction implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
            DataBaseConnector db = new DataBaseConnector();

            db.viewData();
        }
    }



    public static void main(String[]args)
    {
        new DatabaseUI();
    }
}

在这种情况下,我需要通过右键单击数据库节点>启动服务器手动启动derby(我正在使用NetBeans).这是一个嵌入式数据库,这意味着我要将它从一台计算机带到另一台计算机,并愿意通过双击jar文件来开始,而不是在每台计算机上都配置数据库并手动启动它们.但是,如果我没有手动启动数据库,则会收到错误

In this case, I need to start the derby manually (I am using NetBeans) by right clicking clicking on database node > start server. This is an embedded database, which means I am taking this from one machine to another and willing to start just by double clicking on the jar file, and not configuring database in each and every machine and starting them manually. But, if I didn't start the database manually, I get an error

java.sql.SQLNonTransientConnectionException:java.net.ConnectException :错误消息连接到端口1527的服务器本地主机时出错 连接被拒绝:连接.

java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.

即使在NetBeans内部,如果我没有手动启动它,也会出现错误.如何在程序中启动Derby,而无需手动启动它?我尝试了一些方法,例如"create=true"参数,NetworkServer.start(),但效果不佳.但是,我不确定我是否正确执行了操作.

No matter even inside NetBeans, if I didn't start it manually, the error comes. How I can start the Derby inside my program, without manually starting it? I have tried some ways like "create=true" parameter, NetworkServer.start(), but no good. However I am not sure whether I did it correctly.

推荐答案

这是一个嵌入式数据库,这意味着我要将其从一台计算机转移到另一台计算机,并愿意通过双击jar文件来开始,

This is a embedded database, which means I am taking this from one machine to another and willing to start just by double clicking on the jar file,

对于derby,嵌入式数据库意味着该数据库在JVM中运行并写入文件系统.这意味着您可以随意移动jar文件,但是如果使用嵌入式数据库,则在其上运行程序的每台计算机都将拥有自己的单独数据库,并且只有一个JVM可以在一个数据库中使用该数据库.时间.那是你想要的吗?

In the case of derby, an embedded database means that the database runs in the JVM and writes to the file system. Which implies that you can move the jar file around like you want, but if you use an embedded database, then each machine that you run the program on will have its own separate database, and one and only one JVM can use that database at a time. Is that what you want?

如果是,则问题是程序使用的URL. "jdbc:derby://localhost:1527/contact;create=true"是一个URL,它告诉DriverManager连接到远程数据库.程序首先加载嵌入式驱动程序并不重要.

If so, the problem is the URL that the program uses. "jdbc:derby://localhost:1527/contact;create=true" is a URL that tells DriverManager to connect to a remote database. It doesn't matter that program loads the embedded driver first.

Derby中的嵌入式URL看起来像这样. jdbc:derby:bar;create=true,它将使用Derby系统主目录或当前工作目录之外的bar目录中的嵌入式数据库.有关嵌入式网址的详细信息,请参见连接到文件-基于derby的数据库.

An embedded URL in Derby looks something like this. jdbc:derby:bar;create=true which will use an embedded database in the bar directory off of the Derby system home or current working directory. For more information on embedded urls, see here connecting to a file-based derby database.

这篇关于以编程方式启动Derby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆