Week 5 Flashcards

1
Q

What is the difference between a simple statement and a prepared statement in JDBC?

A

A simple statement is used for executing a single SQL query directly. A prepared statement is precompiled and can be reused with different parameters, improving performance and security.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write an example of using a prepared statement in Java to insert data into a database.

A

PreparedStatement pstmt = connection.prepareStatement(“INSERT INTO users (name, email) VALUES (?, ?)”);

pstmt.setString(1, “John Doe”);

pstmt.setString(2, “john@example.com”);

pstmt.executeUpdate();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain how prepared statements help in preventing SQL injection attacks.

A

Prepared statements use parameterized queries, which separate SQL code from data, preventing malicious input from altering the query structure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do prepared statements help in improving performance?

A

Prepared statements are precompiled and can be executed multiple times with different parameters without the overhead of compiling the SQL statement each time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can you reuse a prepared statement in JDBC? How?

A

Yes, prepared statements can be reused. Once prepared, you can set different parameters and execute the statement multiple times.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write an example of using a simple statement to execute a query in Java.

A

Statement stmt = connection.createStatement();

ResultSet rs = stmt.executeQuery(“SELECT * FROM users”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are some scenarios where you would prefer using a simple statement over a prepared statement?

A

You might use a simple statement for executing static queries or when performance is not a concern. However, prepared statements are preferred for dynamic user inputs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is parameter binding in prepared statements, and how does it work?

A

Parameter binding allows you to specify placeholders in the SQL query (e.g., ?) and then set values for these placeholders using methods like setString(), setInt(), etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why is it not recommended to use simple statements with dynamic SQL queries?

A

Concatenating user inputs in SQL queries can lead to SQL injection, as malicious users can manipulate the input to alter the query logic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does a prepared statement handle queries with user input compared to a simple statement?

A

Prepared statements ensure that user input is treated as data, not executable code, thus protecting against SQL injection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What common information is stored in a JDBC properties file?

A

JDBC properties files typically include database URL, username, password, driver class name, and any additional connection properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a JDBC properties file, and why is it used?

A

A JDBC properties file is a configuration file that contains database connection parameters (like URL, username, and password) to simplify database access in Java applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can you load a JDBC properties file in a Java application?

A

Properties props = new Properties();

try (InputStream input = new FileInputStream(“db.properties”)) {
props.load(input);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can you retrieve database connection details from a JDBC properties file in Java?

A

String url = props.getProperty(“db.url”);

String user = props.getProperty(“db.user”);

String password = props.getProperty(“db.password”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does using a properties file simplify database configuration?

A

It centralizes configuration settings, making it easier to modify connection parameters without changing the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Write a sample JDBC properties file for a MySQL database connection.

A

db.url=jdbc:mysql://localhost:3306/mydb
db.user=root
db.password=secret
db.driver=com.mysql.jdbc.Driver

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can you change the database configuration dynamically using a properties file?

A

You can use encryption for sensitive data or restrict access to the properties file through file permissions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Can you secure sensitive information in a JDBC properties file? If so, how?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are some best practices for maintaining and using JDBC properties files?

A

By editing the properties file, you can change connection settings without recompiling the application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How can you handle exceptions when loading a JDBC properties file?

A

Keep the properties file outside the source code, avoid hardcoding sensitive information, and document configuration options.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a utility class in the context of JDBC, and why is it useful?

A

Use try-catch blocks when loading the properties file to handle potential IOException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you set up a utility class for managing database connections in Java?

A

A utility class can be set up by creating a class with methods for opening and closing database connections.

public class DBUtil {

public static Connection getConnection() { /* implementation */ }

public static void closeConnection(Connection conn) { /* implementation */ } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What methods should a JDBC utility class contain to manage connections effectively?

A

Methods for getting a connection, closing connections, handling transactions, and error logging.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Write a sample utility class that provides a method to get a database connection.

A

public class DBUtil {
private static final String URL = “jdbc:mysql://localhost:3306/mydb”;
private static final String USER = “root”;
private static final String PASSWORD = “secret”;

public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(URL, USER, PASSWORD);
}

public static void closeConnection(Connection conn) {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* handle exception */ }
    }
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the purpose of a closeConnection method in a utility class?

A

It releases database resources, preventing memory leaks and connection exhaustion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How can you ensure thread safety when using a utility class for database connections?

A

Use synchronized methods or implement a connection pool (like HikariCP) to manage multiple concurrent connections safely.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Explain how connection pooling can be integrated into a JDBC utility class.

A

Use a connection pooling library that maintains a pool of connections to be reused, reducing overhead for frequent connections.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How can you improve the reusability of a utility class in large-scale applications?

A

Design utility methods to be general-purpose, allowing them to be used across various parts of the application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How can you implement exception handling in a JDBC utility class?

A

Include try-catch blocks to handle SQL exceptions in your utility methods and log errors appropriately.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are the benefits of using a utility class to manage JDBC resources?

A

A utility class abstracts database operations, leading to cleaner code, easier maintenance, and better separation of concerns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is SQL injection, and how does it occur?

A

SQL injection is a code injection technique where an attacker can manipulate SQL queries by injecting malicious input.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is cumulative SQL injection, and how does it differ from a simple SQL injection?

A

This refers to multiple sequential injections that build upon each other to exploit vulnerabilities, leading to more complex attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How can cumulative SQL injection be prevented in Java applications?

A

Use prepared statements, parameterized queries, input validation, and whitelisting to prevent cumulative SQL injection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Provide an example of a vulnerable query that is susceptible to cumulative SQL injection.

A

String query = “SELECT * FROM users WHERE username = ‘” + username + “’”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

How can you use prepared statements to prevent cumulative SQL injection?

A

PreparedStatement pstmt = connection.prepareStatement(“SELECT * FROM users WHERE username = ?”);
pstmt.setString(1, username);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What are some common indicators of SQL injection attacks in database logs?

A

Unusual database error messages, unexpected query results, or logs showing suspicious query patterns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Explain how user input can be sanitized to prevent SQL injection.

A

Validate user inputs by checking against expected formats or allowed values before processing them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What role does input validation play in preventing cumulative SQL injection?

A

It ensures that only valid data is accepted, preventing potentially malicious input from being executed in SQL queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How can you test a web application for SQL injection vulnerabilities?

A

Use automated tools or manual testing methods to input typical SQL injection payloads into forms or API endpoints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What are the consequences of cumulative SQL injection attacks?

A

Data breaches, unauthorized access, data corruption, and potential loss of reputation for organizations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What are the best practices to prevent SQL injection in Java applications?

A

Use prepared statements, parameterized queries, input validation, stored procedures, and ORM frameworks to reduce risks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Why is it important to avoid concatenating user inputs in SQL queries?

A

Concatenating user inputs in SQL queries can allow attackers to inject SQL code; always use parameterized queries instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the role of parameterized queries in preventing SQL injection?

A

They separate SQL code from data, ensuring that user input is treated as data rather than executable code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How do ORM tools (like Hibernate) help in preventing SQL injection?

A

ORM frameworks automatically handle input sanitization and parameter binding, minimizing SQL injection risks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Explain how whitelisting input can prevent SQL injection attacks.

A

Define and enforce acceptable input patterns, rejecting any input that does not conform to the defined criteria.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

How can you use regular expressions to validate user input and prevent SQL injection?

A

Use regex patterns to ensure that user inputs conform to expected formats (e.g., email addresses).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What security practices can be implemented at the database level to prevent SQL injection?

A

Implement role-based access control, least privilege principle, and avoid using administrative accounts for application access.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

How can stored procedures help in preventing SQL injection?

A

Use stored procedures to encapsulate SQL logic, as they can help mitigate injection risks if properly implemented.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Why is it important to minimize database user permissions in the context of SQL injection prevention?

A

Limit the database permissions of the application user to only the necessary actions, reducing the impact of a successful injection.

45
Q

What is the role of logging in identifying and mitigating SQL injection attempts?

A

Monitoring and logging attempts can help identify attack patterns and respond quickly to potential SQL injection attempts.

46
Q

What is a composite key in a relational database?

A

A composite key is a primary key that consists of two or more columns in a table, uniquely identifying a row.

47
Q

How is a composite key different from a primary key?

A

A primary key can consist of a single column, while a composite key specifically involves multiple columns.

48
Q

Provide an example of when you would use a composite key in database design.

A

In a table of course enrollments, the composite key could be (student_id, course_id), ensuring that each student can enroll in a course only once.

49
Q

Can a composite key have more than two columns? If yes, explain how.

A

Yes, a composite key can include more than two columns, allowing for unique identification based on combined values.

50
Q

What is the significance of a composite key in ensuring data integrity?

A

Composite keys help maintain data integrity by ensuring that the combination of values in the key columns is unique across the table.

50
Q

How do you define a composite key in an SQL table?

A

CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);

51
Q

What are some challenges of using composite keys in database design?

A

Composite keys can complicate queries and foreign key references, making the database

51
Q

How does a composite key influence indexing and query performance?

A

Composite keys can improve query performance for specific queries that utilize all the key columns in their filters.

51
Q

Can a composite key include both foreign and primary keys? Explain with an example.

A

Yes, a composite key can include a foreign key, such as linking a student’s enrollment to the corresponding student and course tables.

52
Q

What is Boyce-Codd Normal Form (BCNF), and when is it used?

A

A table is in BCNF if it is in 3NF and every determinant is a candidate key, ensuring that non-trivial functional dependencies are always on superkeys.

52
Q

What is Second Normal Form (2NF), and how does it differ from 1NF?

A

A table is in 2NF if it is in 1NF and all non-key attributes are fully functionally dependent on the primary key. It eliminates partial dependency.

52
Q

What is database normalization, and why is it important?

A

Database normalization is the process of organizing data to reduce redundancy and improve data integrity, making it easier to maintain.

52
Q

How would you reference a composite key in another table as a foreign key?

A

CREATE TABLE grades (
student_id INT,
course_id INT,
grade CHAR(2),
FOREIGN KEY (student_id, course_id) REFERENCES enrollments(student_id, course_id)
);

52
Q

Explain the concept of First Normal Form (1NF) with an example.

A

A table is in 1NF if all columns contain atomic values, and each entry in a column is of the same data type. For example, a column should not have lists or sets.

52
Q

How does 3NF differ from BCNF?

A

In BCNF, every functional dependency is on a candidate key, while in 3NF, dependencies can exist on non-key attributes as long as they do not create transitive dependencies.

52
Q

Provide an example of a table that is in 1NF but not in 2NF.

A

1 | Math, Sci | Smith

The Course column contains non-atomic values.

53
Q

Describe Third Normal Form (3NF) and its importance in database design.

A

A table is in 3NF if it is in 2NF and all attributes are functionally dependent only on the primary key, eliminating transitive dependency.

54
Q

What are the potential drawbacks of over-normalizing a database?

A

It can lead to complex queries and may impact performance due to excessive joins, making data retrieval slower.

55
Q

Explain how normalization affects the performance of read-heavy databases.

A

Normalization can lead to improved data integrity but may slow down read-heavy databases that require complex joins.

56
Q

When would you deliberately choose not to fully normalize a database?

A

In cases where performance is critical, you may choose to denormalize to optimize read operations at the expense of data integrity.

57
Q

What does multiplicity mean in the context of data modeling?

A

Multiplicity indicates the number of instances of one entity that can or must be associated with instances of another entity in a relationship.

58
Q

How is multiplicity represented in an ER diagram?

A

Multiplicity is typically shown using notations like 1, 0..1, or * (many) next to the entities involved in the relationship.

59
Q

Provide an example of a one-to-many relationship and explain its multiplicity.

A

In a relationship between Customer and Order, one customer can place multiple orders, represented as 1 to *.

60
Q

What is a many-to-many relationship, and how is it resolved in relational databases?

A

This relationship is resolved by creating a junction table (also known as a bridge table) that holds foreign keys from both related entities.

61
Q

How does multiplicity influence the design of foreign key constraints?

A

Multiplicity determines how foreign keys are defined in the related tables, ensuring referential integrity based on the nature of relationships.

62
Q

What is the difference between multiplicity and cardinality in ER modeling?

A

Cardinality refers to the number of instances in a relationship, while multiplicity specifies the constraints on those instances.

63
Q

Can multiplicity constraints be enforced at the database level? If so, how?

A

Yes, multiplicity constraints can be enforced using foreign key relationships and application-level logic.

64
Q

What is data modeling, and why is it important in database design?

A

Data modeling is the process of creating a conceptual representation of data structures and relationships, facilitating database design and management.

64
Q

How would you model a one-to-one relationship in a relational database?

A

This is represented by having a unique constraint on both related tables, ensuring that each instance corresponds to a single instance in the other table.

65
Q

What is an Entity-Relationship Diagram (ERD), and what does it represent?

A

An ERD visually represents entities, attributes, and the relationships between them in a database.

66
Q

Explain the difference between entities and attributes in ER modeling.

A

Entities are objects or concepts (like Customer), while attributes are the properties or characteristics of those entities (like Customer Name).

67
Q

How do relationships between entities get represented in an ERD?

A

Relationships between entities are shown as lines connecting them, often labeled to indicate the nature of the relationship (e.g., one-to-many).

68
Q

What is the role of primary keys and foreign keys in an ERD?

A

Primary keys uniquely identify rows in a table, while foreign keys establish a link between tables, enabling relationships.

69
Q

What is a weak entity, and how is it represented in an ERD?

A

A weak entity cannot be uniquely identified by its attributes alone and relies on a “strong” entity’s primary key. It is represented by a double rectangle in ERDs.

70
Q

How do you represent a many-to-many relationship in an ERD?

A

It is modeled by creating a junction table that includes foreign keys referencing both related entities.

71
Q

How does normalization relate to ERD creation?

A

Normalization is applied to the entities and attributes identified in an ERD to ensure data integrity and eliminate redundancy.

71
Q

What are the key differences between logical and physical ERDs?

A

Logical ERDs focus on the structure of the data and relationships without concern for how they will be implemented, while physical ERDs include details about how data is stored in the database.

72
Q

What is a cross join in SQL, and how does it work?

A

A cross join produces a Cartesian product of two tables, combining all rows from the first table with all rows from the second.

73
Q

Provide an example of a query using a cross join.

A

SELECT * FROM table1 CROSS JOIN table2;

74
Q

When should you avoid using a cross join in SQL queries?

A

Cross joins can result in large result sets; avoid using them unless necessary for specific analytical scenarios.

75
Q

Provide an example of a query that uses a self join to retrieve hierarchical data.

A

SELECT a.name AS Employee, b.name AS Manager
FROM employees a
JOIN employees b ON a.manager_id = b.id;

75
Q

What is a self join in SQL, and when would you use it?

A

A self join is a join that is performed on a single table, where the table is treated as two different entities to compare rows.

76
Q

What is the difference between a cross join and an inner join?

A

An inner join returns only matching rows from both tables based on a specified condition, while a cross join returns all possible combinations.

77
Q

How can you create a view in SQL, and what is its purpose?

A

CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;

78
Q

How does a self join differ from other types of joins in SQL?

A

A self join uses the same table to compare rows within it, unlike other joins which connect different tables.

79
Q

What are set operators in SQL, and what are their common types?

A

Set operators in SQL combine the results of two or more queries. Common types include UNION, INTERSECT, and EXCEPT.

80
Q

Explain the difference between UNION and UNION ALL with examples.

A

UNION combines the results of two queries and removes duplicates, while UNION ALL includes all duplicates.

81
Q

When would you use the INTERSECT operator in SQL?

A

The INTERSECT operator returns only the rows that are common to both queries.

SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;

82
Q

Provide an example of a query using the EXCEPT operator.

A

The EXCEPT operator returns rows from the first query that are not found in the second query.

SELECT column_name FROM table1
EXCEPT
SELECT column_name FROM table2;

83
Q

What is a view in SQL, and how does it differ from a table?

A

A view is a virtual table in SQL that provides a way to present data from one or more tables without storing it physically.

Difference from a Table: A view does not store data itself; it retrieves data dynamically from the underlying tables when queried

84
Q

Can views be updated in SQL? If so, explain how.

A

Some views can be updated, but only if they meet specific criteria, such as having a direct mapping to a single table with no aggregate functions.

85
Q

What is an index in SQL, and why is it used?

A

An index is a database object that improves the speed of data retrieval operations on a table.

86
Q

Explain the difference between clustered and non-clustered indexes.

A

A clustered index determines the physical order of data in the table, while a non-clustered index is a separate structure that points to the data rows.

87
Q

What is HTTP, and what role does it play in web communication?

A

HTTP (Hypertext Transfer Protocol) is an application protocol used for transferring data over the web, enabling communication between clients and servers.

87
Q

How can you create an index on a table in SQL?

A

CREATE INDEX index_name ON table_name (column_name);

87
Q

What are the benefits of using indexes in SQL queries?

A

Indexes can significantly speed up SELECT queries, improve performance on JOIN operations, and enhance the efficiency of WHERE clauses.

88
Q

How does the client-server model work in the context of HTTP?

A

The client sends requests to the server, which processes those requests and sends back responses, allowing for resource sharing and communication.

89
Q

Explain the difference between HTTP and HTTPS.

A

HTTPS (HTTP Secure) is an extension of HTTP that uses encryption (SSL/TLS) to secure data exchanged between clients and servers.

90
Q

What are HTTP verbs, and why are they important in RESTful APIs?

A

HTTP verbs (methods) specify the action to be performed on a resource, crucial for RESTful APIs to define how to interact with resources.

91
Q

Explain the difference between GET and POST HTTP methods.

A

GET requests retrieve data from the server, while POST requests submit data to the server to create or update a resource.

92
Q

What is the purpose of the PUT HTTP verb?

A

The PUT method is used to update an existing resource or create a new resource if it does not already exist.

93
Q

When would you use the DELETE HTTP verb in an API?

A

The DELETE method removes a specified resource from the server.

94
Q

What are HTTP status codes, and what do they represent?

A

HTTP status codes are standard responses issued by servers to indicate the outcome of a client’s request.

95
Q

Explain the meaning of status code 200 (OK).

A

Request succeeded.

96
Q

What does HTTP status code 404 represent?

A

Requested resource not found

97
Q

When would you receive a 500 Internal Server Error?

A

Server encountered an error.

98
Q

What is the difference between “frontend” and “backend” in web development?

A

Frontend: Client side; what users see and interact with (HTML, CSS, JavaScript).
Backend: Server side; manages data and application logic (Java, Python, databases).

99
Q

Explain what is meant by the term “full-stack developer.”

A

A developer proficient in both frontend and backend technologies, capable of handling all aspects of web development.

100
Q

What is a “pull request,” and how does it fit into version control?

A

A request to merge code changes from a feature branch into the main codebase, facilitating code review and collaboration before integration.

101
Q

What does “debugging” mean in software development?

A

The process of identifying, analyzing, and fixing bugs in software. It includes reproducing issues, diagnosing code, and verifying fixes.