Connecting Java to a Database with JDBC

Day 18 —#100DaysJava today Java connected to a database for the first time. That felt real. ☕ For 17 days I have been writing Java code that runs and stops. Data lives for one second and disappears. Today I learned JDBC — and now data can actually be saved, fetched, updated, and deleted. Permanently. This is where Java starts feeling like a real backend language. --- What is JDBC? JDBC stands for Java Database Connectivity. It is the bridge between your Java code and a database like MySQL or PostgreSQL. Without JDBC — Java cannot talk to a database. With JDBC — Java can run SQL queries directly from your code. --- How it works — 5 simple steps every Java developer should know: Step 1 — Load the driver Tell Java which database you are connecting to. Class.forName("com.mysql.cj.jdbc.Driver"); Step 2 — Create a connection Give the database URL, username, and password. Connection con = DriverManager.getConnection(url, user, password); Step 3 — Create a statement Prepare the SQL query you want to run. Statement st = con.createStatement(); Step 4 — Execute the query Run SELECT, INSERT, UPDATE, or DELETE. ResultSet rs = st.executeQuery("SELECT * FROM users"); Step 5 — Close the connection Always close after use. Never leave it open. con.close(); --- The thing that surprised me — PreparedStatement vs Statement. Statement is simple but dangerous. If you put user input directly into a SQL query, a hacker can inject malicious SQL and destroy your database. This is called SQL Injection. PreparedStatement is safe. You use placeholders — ? — and Java handles the input safely. Every real application uses PreparedStatement. Never Statement with user input. PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?"); ps.setInt(1, userId); --- Also learned today — CRUD operations: CREATE → INSERT INTO READ → SELECT UPDATE → UPDATE SET DELETE → DELETE FROM These four operations are the foundation of every backend application ever built. --- What clicked today — every app I have ever used stores data somewhere. Instagram saves your photos. Zomato saves your orders. Swiggy saves your address. JDBC is the layer that makes that possible in Java. 17 days in. The journey is getting more real every single day. 💪 Day 1 ................................................... Day 18 To any backend developer reading this — what was your first database connection moment like? Did it feel as satisfying as it did for me today? 🙏 #Java #JDBC #Database #MySQL #BackendDevelopment #100DaysOfJava #JavaDeveloper #LearningInPublic #100DaysOfCode #SQL #WebDevelopment #Programming

To view or add a comment, sign in

Explore content categories