Java, Python, Database, Flutter, Matlap, Micorcontroller, Tutorials, Swing Framework

Hancie e-Learning Studio

Learn Java, Learn HTML, CSS, PHP, Javascript, Python Tutorials || Download program source codes || Java Project and Source code available here || All types error troubleshooting tips available here

How to insert data into SQLite database in Java Swing?

 


GUI.java
package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class GUI {
	JTextField txt, id;

	public GUI() {

		JFrame f = new JFrame("Hancie e-Learning Studio");
		f.setSize(720, 400);
		f.setLocationRelativeTo(f);
		f.setLayout(null);

		id = new JTextField();
		id.setBounds(10, 50, 200, 30);
		f.add(id);

		txt = new JTextField();
		txt.setBounds(10, 10, 200, 30);
		f.add(txt);

		JButton btn = new JButton("Insert");
		btn.setBounds(10, 100, 100, 30);
		f.add(btn);
		btn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				Connection conn;
				PreparedStatement pstat;
				String sql = "INSERT INTO Hancie (ID,Name) VALUES (?,?);";
				try {

					Class.forName("org.sqlite.JDBC");
					String URL = "jdbc:sqlite:C:/Users/Hanci/Desktop/database.db";
					conn = DriverManager.getConnection(URL);

					pstat = conn.prepareStatement(sql);
					pstat.setInt(1, Integer.parseInt(id.getText()));
					pstat.setString(2, txt.getText());
					pstat.execute();

					conn.close();
					JOptionPane.showMessageDialog(null, "Stored");

				} catch (Exception ex) {
					JOptionPane.showMessageDialog(null, "Error55" + ex.getMessage());
				}

			}

		});

		f.setVisible(true);

	}

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

	}

}
Output
Welcome all to Hancie e-learning studio
Friends,
I have brought an e-learning platform for you from where you can teach internet, website, programming language, error troubleshooting, etc. Blogger, WordPress templates, themes are available for free on this website, which are not charged for downloading, so that you can earn money by blogging using such templates and this is not a difficult task and this You can do it now. You keep uploading new posts by us and keep taking advantage of this website. The aim of which is to spread the knowledge related to internet, career, web designing and technology to the people and contribute to the development of the country.